2013-05-09 91 views
0

得到的childNodes我有喜歡的xml:從XML節點

<?xml version="1.0" encoding="utf-8" ?> 
<response list="true"> 
    <count>10748</count> 
    <post> 
     <id>164754</id> 
     <text></text> 
     <attachments list="true"> 
      <attachment> 
       <type>photo</type> 
       <photo> 
        <pid>302989460</pid> 
       </photo> 
      </attachment> 
     </attachments> 

我需要檢查,如果在我的<post><attachment>。 我得到的所有帖子是這樣的:

XmlNodeList posts = XmlDoc.GetElementsByTagName("post"); 
foreach (XmlNode xnode in posts) 
{ 
    //Here I have to check somehow 
} 

如果在後無<attachment>節點,我想它的<text>代替。

+0

你要得到什麼?元素或值的列表? – lexeRoy 2013-05-09 00:50:16

回答

1

如果您從XmlDocument更改爲XElement,則可以使用LINQ查詢來獲取attachment節點的數量。

//load in the xml 
XElement root = XElement.Load("pathToXMLFile"); //load from file 
XElement root = XElement.Parse("someXMLString"); //load from memory 

foreach (XElement post in root.Elements("post")) 
{ 
    int numOfAttachNodes = post.Elements("attachments").Count(); 

    if(numOfAttachNodes == 0) 
    { 
     //there is no attachment node 
    } 
    else 
    { 
     //something if there is an attachment node 
    } 
} 
-1

要檢查是否有「帖子」的任何節點:在開始循環之前

if(posts.Count == 0) 
{ 
    // No child nodes! 
} 

你能做到這一點。

+0

-1。這將檢查子節點的總數,但不會將「附件」節點與「文本」節點區分開來。 – gunr2171 2013-05-09 00:56:01

0

你可以嘗試LINQ查詢它會是這樣

var result = XmlDoc.Element("response") 
        .Elements("post").Select(item => item.Element("attachments")).ToList(); 

foreach(var node in result) 
{ 

} 
+0

問題是他的現有變量使用'XmlDocument'而不是'XElement'。這就是爲什麼我提出使用後者的建議。 – gunr2171 2013-05-09 01:16:09