c# - 如何使用 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
解决方案
我相信您正在获得 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
推荐阅读
- python - 模型和限界上下文如何映射到代码库 DDD 中?
- jsf - 将元数据包含到 JSF
- javascript - 检查使用 AJAX 添加的 JSON 中是否已存在值
- sql-server - 可以使基于行的计数器表现得像 SEQUENCE 或 IDENTITY 吗?
- r - MLR:如何计算顺序 MBO 参数化模型的置换特征重要性?
- php - Yii2 ActiveQuery 一列不等于另一列
- git - git 暂存所有已跟踪并具有特定扩展名的文件
- html - 在 Django 模板中访问字典
- python - Python Bokeh 标记文本值无法更新
- c# - 根据开始/结束事件对反应流中的事件进行分组