【发布时间】:2014-01-09 16:52:27
【问题描述】:
我有一个这样的 xml 文件:
<post>
<categories>
<category ref="4527" />
<category ref="4528" />
<category ref="4529" />
<category ref="4530" />
<category ref="4531" />
</categories>
</post>
<post>
<categories>
<category ref="4523" />
<category ref="4524" />
<category ref="4525" />
<category ref="4526" />
<category ref="4527" />
</categories>
</post>
使用 C# 和 .Net 4.5 我想获取第一组类别参考编号,然后处理它们,然后移动到下一组类别参考编号并处理它们。我希望有人能指出我正确的方向。我不确定如何使用 XPath 或 Linq to XML 执行此操作,或者这些方法是否正确。提前致谢。
在回复了一些非常聪明的人之后,我能够使用 Selman22 的思路来帮助我编写一些 XPath。这是我想出的解决方案:
XmlDocument xdoc = new XmlDocument;
xdoc.Load(savePath);
XmlNode root = xdoc.DocumentElement;
// add the namespace
XmlNamespaceManager nsmgr = new XmlNamespaceManager(xdoc.NameTable);
nsmgr.AddNamespace("bml", "http://www.blogml.com/2006/09/BlogML");
//puts the catagories elements into a list
XmlNodeList blogCatagories = root.SelectNodes("descendant::bml:post/bml:categories", nsmgr);
//loop throught list and place the attribute "ref" into a list and traverse each "ref"
foreach (XmlNode nodeCat in blogCatagories)
{
XmlNodeList catagoryids = nodeCat.SelectNodes("descendant::bml:category/@ref", nsmgr);
foreach (XmlNode nodeID in catagoryids)
{
Console.WriteLine(nodeID.InnerText.ToString());
}
}
【问题讨论】:
-
@SergeyBerezovskiy see this on meta
标签: c# .net xml xpath linq-to-xml