我有代碼解析XML,看起來像這樣:的LINQ to XML相當於XPath的
<custom_fields>
<custom_field>
<column_name>foo</column_name>
<column_value>0</column_value>
<description>Submitted</description>
<data_type>BOOLEAN</data_type>
<length>0</length>
<decimal>0</decimal>
</custom_field>
<custom_field>
<column_name>bar</column_name>
<column_value>0</column_value>
<description>Validated</description>
<data_type>BOOLEAN</data_type>
<length>0</length>
<decimal>0</decimal>
</custom_field>
</custom_fields>
... more <custom_field> elements...
我想找到的元素稱爲custom_field
具有某一個值,稱爲column_name
的子元素(例如bar
),然後找到那個叫做column_value
的孩子的兄弟姐妹並獲得它的價值。現在,我使用上XMlDocument
XPath來做到這一點:
string path = "//custom_fields/custom_field[column_name='" + key + "']";
XmlNode xNode = doc.SelectSingleNode(path);
if (xNode != null)
{
XmlNode v = xNode.SelectSingleNode("column_value");
val.SetValue(v.InnerText);
}
哪裏key
是我要找的字段的名稱。
但我想在XDocument
上使用新的LINQ to XML語法來完成此操作。我的想法是,我將大部分舊式XPath解析轉移到LINQ方法中。也許這不是一個好主意,但是如果我能夠實現它,那麼我相信我會對LINQ有更好的理解,並且能夠清理很多複雜的代碼。
的可能的複製[?如何使用XPath用的XElement或LINQ(http://stackoverflow.com/questions/3642829/how -to-use-xpath-with-xelement-or-linq) – 2016-09-01 07:13:21