[英]getting childnodes from xml node
我有像這樣的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>
<post>
。 我正在收到所有這樣的帖子:
XmlNodeList posts = XmlDoc.GetElementsByTagName("post");
foreach (XmlNode xnode in posts)
{
//Here I have to check somehow
}
如果帖子中沒有<attachment>
節點,那么我想獲取其<text>
。
如果從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
}
}
您可以嘗試一個linq查詢,就像這樣
var result = XmlDoc.Element("response")
.Elements("post").Select(item => item.Element("attachments")).ToList();
foreach(var node in result)
{
}
要檢查“帖子”中是否有任何節點:
if(posts.Count == 0)
{
// No child nodes!
}
您可以在開始循環之前執行此操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.