【问题标题】:How to get substrings from an Xpath using C#?如何使用 C# 从 Xpath 获取子字符串?
【发布时间】:2019-09-27 11:44:46
【问题描述】:

我在 JSON 文件中有一个 Xpath 属性,我想从此 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

【问题讨论】:

  • 到目前为止您尝试了什么?向我们展示你的尝试。提示:你可以使用Split('/').Last()
  • 我已经在主要问题中添加了我的尝试,你可以检查一下。

标签: c# string xpath substring


【解决方案1】:

我相信您在matchString[index].xpath 中获得了 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 fiddle

【讨论】:

  • 非常感谢,这正是我要找的。​​span>
  • 很高兴我的回答有帮助。请接受答案,以便其他人阅读
【解决方案2】:

使用Regex (Link to formula)

var obj = JObject.Parse("your_json");
var xpath = ((JArray)obj["matchString"])[0]["xpath"].Value<string>();

string pattern = "(?<=key=\")(.*?)(?=\").*(?<=value=\")(.*?)(?=\")";
var match = new Regex(pattern).Match(xpath);

string key = match.Groups[1].Value;   
string value = match.Groups[2].Value;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-19
    • 2014-12-13
    • 1970-01-01
    • 1970-01-01
    • 2011-05-25
    • 2011-11-05
    相关资源
    最近更新 更多