[英]how to read from the xml node using c# as per my requirement
這是我的xml代碼:
<?xml version="1.0" encoding="utf-8"?>
<xd:xmldiff version="1.0" srcDocHash="11928043053884448382" options="IgnoreChildOrder IgnoreNamespaces IgnoreWhitespace IgnoreXmlDecl " fragments="no" xmlns:xd="http://schemas.microsoft.com/xmltools/2002/xmldiff">
<xd:node match="2">
<xd:node match="2">
<xd:node match="19">
<xd:node match="2">
<xd:add>Y</xd:add>
</xd:node>
</xd:node>
<xd:add match="/2/2/11" opid="2" />
<xd:change match="18" name="OWNINGSITE">
<xd:node match="2">
<xd:remove match="1" />
</xd:node>
</xd:change>
<xd:add match="/2/2/2-9" opid="1" />
<xd:change match="17" name="STATUS">
<xd:node match="2">
<xd:remove match="1" />
</xd:node>
</xd:change>
<xd:remove match="14-16" />
<xd:remove match="13" subtree="no">
<xd:remove match="1-2" />
</xd:remove>
<xd:remove match="11" opid="2" />
<xd:remove match="10" />
<xd:remove match="2-9" opid="1" />
<xd:remove match="1" />
</xd:node>
<xd:node match="5">
<xd:node match="3">
<xd:node match="11">
<xd:change match="1">0,1,0,1,0,0,0,0,1</xd:change>
</xd:node>
</xd:node>
</xd:node>
</xd:node>
<xd:descriptor opid="1" type="move" />
<xd:descriptor opid="2" type="move" />
</xd:xmldiff>
我已經編寫了ac#代碼來解析每個節點並獲取match的值。 我無法弄清楚如何解析節點以獲取所有匹配項的值。 在調試代碼時,我發現nodelist無法通過“ xmlDoc.DocumentElement.SelectNodes(” / node“);”接收到適當的值。 由於哪個foreach根本沒有執行。 我對“ / node”的使用是否正確以獲得其屬性“ match”的值?
namespace demo
{
class Program
{
static void Main()
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("C:\\shreyas\\NX_Temp\\NX_Temp\\000048_A\\CompareReport3D.xml");
XmlNodeList nodeList = xmlDoc.DocumentElement.SelectNodes("/node");
string[] arr1 = new string[10];
int i = 0;
foreach (XmlNode node in nodeList)
{
arr1[i] = node.Attributes["match"].Value;
i++;
}
i = 0;
while (arr1[i] != null)
{
Console.WriteLine("the String=" + arr1[i]+ ":" + arr1[i++]+ ":" + arr1[i++]+":" + arr1[i++]);
}
}
}
}
我需要以字符串形式找到“匹配”的值
輸出應為: the String = 2:2:19:2
最簡單的方法是使用遞歸。
編寫一個帶有XmlNode node
, string currentPath
和List<string> paths
的函數。 這應該:
node
的match
屬性附加到currentPath
並檢查該node
是否具有屬於node
的子node
。 currentPath
添加到paths
並返回。 currentPath
(已修改)和paths
來為每個子代調用自身。 首先,您將使用根節點,一個空字符串和一個空列表來調用此函數。 函數完成后,以前為空的列表將包含您的路徑,例如您的示例的兩個路徑:
您可以使用Regex匹配要查找的所有屬性:
// Find all attributes that match the pattern match="x" - where x can be any value.
foreach (var match in Regex.Matches(str, "match=\"([^\"]+)\""))
{
// For each match, match only the "x" part of the result and remove the containing ".
Console.WriteLine(Regex.Match(match.ToString(), "\"([^\"]+)\"").ToString()
.Replace("\"", string.Empty));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.