簡體   English   中英

如何直接從xml獲取值(最好使用XPath)?

[英]How to get a value from an xml directly (preferably using XPath)?

我試圖在C#中以最簡單的方式獲取comp1的值。 我希望能夠以一種需要最少檢查像Primary這樣的元素存在的方式來做到這一點。

//  pseudo code
xmlItem = root.SelectSingleNode "/Primary/Complex?Name='comp1'"

因此,我只能檢查xmlItem是否為null或沒有元素,而不是每次訪問子節點時xmlItem進行很多檢查。 這是xml,但實際的嵌套得更多,但是只有葉子xml節點具有我們要查找的特定名稱。

<?xml version="1.0" ?>
<Primary Type="">
   <Simple Name="smp"></Simple>
   <Complex Name="comp0" Value="123"></Complex>
   <Complex Name="comp1" Value="456"></Complex>
   <Complex Name="comp2" Value="789"></Complex>
</Primary>

我認為XPath是/Primary/Complex[@Name='comp0']/@Value

順便說一句,您的XML是錯誤的。 對於簡單,沒有結束標簽,對於材料,沒有開始標簽。 我假設</Material>應該是</Simple>

var xmlItem = root.SelectSingleNode("/Primary/Complex[@Name='comp1']/@Value");

嘗試

root.SelectSingleNode("/Primary/Complex[@Name='comp1']/@Value");

您將要使用System.Xml.XPath命名空間中的XPathDocument和XPathNavigator。

XPathDocument fileToParse = new XPathDocument(FullPathToFile);
XPathNavigator fileNavigator = fileToParse.CreateNavigator();
XPathNavigator selected = fileNavigator.SelectSingleNode("./Primary/Complex[@Name='comp1']/@Value");
//selected will be null if your XPath doesn't select anything...
if(selected != null){ Console.WriteLine(selected.Value); }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM