我有一個XML文件中像這樣重複:如何通過多個家長XML文件c#子元素
<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到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 [見到這對元(http://meta.stackexchange.com/a/215546/188759) – Amicable