从XML节点
得到的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>
代替。
如果您从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
}
}
要检查是否有“帖子”的任何节点:在开始循环之前
if(posts.Count == 0)
{
// No child nodes!
}
你能做到这一点。
-1。这将检查子节点的总数,但不会将“附件”节点与“文本”节点区分开来。 – gunr2171 2013-05-09 00:56:01
你可以尝试LINQ查询它会是这样
var result = XmlDoc.Element("response")
.Elements("post").Select(item => item.Element("attachments")).ToList();
foreach(var node in result)
{
}
问题是他的现有变量使用'XmlDocument'而不是'XElement'。这就是为什么我提出使用后者的建议。 – gunr2171 2013-05-09 01:16:09
你要得到什么?元素或值的列表? – lexeRoy 2013-05-09 00:50:16