2016-12-01 82 views
-1

這是我的XML內蒙古XML節點..選擇包含幾乎相同的ID

<rootparent> 
    <root> 
    ...other nodes here. 
    ... 
    <parent> 
     <child id="child_1"> 
     .some other nodes .. 
     </child> 
     <child id="child_2"> 
     .some other nodes .. 
     </child> 
     ...other nodes 
    </parent> 
    </root> 
</rootparent> 

我需要select all the child nodes where id like 'child_%'使用LINQ to XML。

我得到了XPath的這一

string xPath="/root/parent/child[id='child_*']"; 
var x1 =xml.XPathSelectElement(xPath); 
var x2 = _sourceDoc.Root.XPathEvaluate(xPath); 

但它返回Enumeration yielded no results

+0

這可能會幫助 - http://stackoverflow.com/questions/18891206/parse-xml-with-linq-to-get-child-elements – Asnivor

+0

我需要使用XPath,我試圖使它generic。@ Asnivor –

回答

1

使用XML LINQ:

string xml = 
    "<rootparent>" + 
     "<root>" + 
     "<parent>" + 
      "<child id=\"child_1\">" + 
      "</child>" + 
      "<child id=\"child_2\">" + 
      "</child>" + 
     "</parent" + 
     "</root>" + 
    "</rootparent>"; 

XDocument doc = XDocument.Parse(xml); 

List<XElement> children = doc.Descendants("child") 
    .Where(x => ((string)x.Attribute("id")).StartsWith("child_")) 
    .ToList(); 
+0

你在這裏沒有使用XPath,我需要利用XPath,因爲我試圖用更一般的方式來做到這一點。 –

+0

如果你想要一個通用的解決方案,你仍然可以使用linq xml。只需使用doc.Descendants()而不是指定「child」。帖子的標題說Linq, – jdweng

+0

@A_Name_Does_Not_Matter:如果你不打算接受linq解決方案,不要這樣標記它。它被標記爲linq-to-xml,所以你得到了一個linq-to-xml的答案。 –

0

對於初學者來說,你的XPath不符合您的XML的結構。您的查詢假定根名爲root,但有rootparent,您不會對它進行解釋。既然你只是在尋找child節點,你甚至不需要引用它,只需要通過後代。

您需要使用適當的條件。你的孩子都沒有包含一個名爲child_*的id元素,所以很自然你不會得到任何結果。使用starts-with函數並訪問id屬性

//child[starts-with(@id, 'child_')]