首页 > 解决方案 > 如何使用 C# 从 Xpath 获取子字符串?

问题描述

Xpath在 JSON 文件中有一个属性,我想从此 Xpath 中获取两个子字符串,以帮助这些子字符串转换为两个变量。

JSON对象如下;

    {
        'selectGateway':'0',
        'waitingTime':'20000',
        'status':'200',
        'correlationID':'1',
        'matchString':[{'xpath':'/whitelist/locations/location/var-fields/var-field[@key="whitelist-entry" and @value="8.0440147AA44A80"]','value':''}],
        'matchInteger':[],
        'matchSortedList':[]

    }

到目前为止,这是我的尝试,它工作正常,我只是在寻找一种方法来更动态地执行此操作,如果可能的话,以更好的方式。

int firstStringPositionForKey = matchString[index].xpath.IndexOf("@key=\"");
int secondStringPositionForKey = matchString[index].xpath.IndexOf("\" and");
string betweenStringForKey = matchString[index].xpath.Substring(firstStringPositionForKey+6, secondStringPositionForKey-firstStringPositionForKey-6);

int firstStringPositionForValue = matchString[index].xpath.IndexOf("@value=\"");
int secondStringPositionForValue = matchString[index].xpath.IndexOf("\"]");
string betweenStringForValue = matchString[index].xpath.Substring(firstStringPositionForValue+8, secondStringPositionForValue-firstStringPositionForValue-8);

我希望输出如下:

key is : whitelist-entry
value is : 8.0440147AA44A80

标签: c#stringxpathsubstring

解决方案


我相信您正在获得 xPath 的价值matchString[index].xpath,所以这里是解决方案

//Test is nothing but your xPath
string test = "/whitelist/locations/location/var-fields/var-field[@key=\"whitelist-entry\" and @value=\"8.0440147AA44A80\"]";

//Split your string by '/' and get last element from it.
string lastElement = test.Split('/').LastOrDefault();

//Use regex to get text present in "<text>"
var matches = new Regex("\".*?\"").Matches(lastElement);

//Remove double quotes         
var key = matches[0].ToString().Trim('\"');
var @value = matches[1].ToString().Trim('\"');;

//Print key and value   
Console.WriteLine("Key is: ${key}");
Console.WriteLine("Value is: ${value}");

输出:

Key is: whitelist-entry
Value is: 8.0440147AA44A80

.net 小提琴


推荐阅读