2011-02-18 48 views
3

我有代碼解析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有更好的理解,並且能夠清理很多複雜的代碼。

+0

的可能的複製[?如何使用XPath用的XElement或LINQ(http://stackoverflow.com/questions/3642829/how -to-use-xpath-with-xelement-or-linq) – 2016-09-01 07:13:21

回答

4

您可以隨時在LINQ to XML中使用XPath。只需包含System.Xml.XPath命名空間。

var xpath = String.Format("//custom_fields/custom_field[column_name='{0}']/column_value", key); 
var custom_field = doc.XPathSelectElement(xpath); 
if (custom_field != null) 
{ 
    val.SetValue((int)custom_field); 
} 

否則爲等效的LINQ to XML查詢:

var custom_field = doc.Descendants("custom_fields") 
         .Elements("custom_field") 
         .Where(cf => cf.Element("column_name").Value == key) // assuming `key` is a string 
         .Elements("column_value") 
         .SingleOrDefault(); 
1

你的XQuery表達式

 
//custom_fields/custom_field[column_name='key'] 

選擇在custom_fields元件,其中column_key子元素的值等於"key"所有custom_field元素。您期望返回一個元素並選擇子元素的值。

可以按如下方式表達這種使用LINQ to XML:

var doc = XDocument.Load(...); 

var query = from fields in doc.Descendants("custom_fields") 
      from field in fields.Elements("custom_field") 
      where (string)field.Element("column_name") == "key" 
      select (int)field.Element("column_value"); 

int result = query.Single(); 
1

我想找到的元素稱爲 custom_field其中有一個名爲列名具有一定 值(例如「子元素 欄」,然後 發現,孩子的兄弟叫 COLUMN_VALUE並得到其數值

用途:

/custom_fields/custom_field[column_name = 'bar']/column_value 
+0

+1表示最短和最佳答案。 – 2011-02-19 15:26:37

+0

使用XPathSelectElement – hB0 2015-02-04 15:52:06