问题描述
我有一个以下格式的 XML 文件:
I have an XML file in the following format:
<categories>
<category id="1"></category>
<category id="2">
<category id="3"></category>
<category id="4">
<category id="5"></category>
</category>
</category>
</categories>
谁能给我一些关于如何使用 C# 遍历文件的指导?
Can anyone please give me some direction on how I might traverse the file using C#?
推荐答案
首先,System.XML 提供了一些使用 XML 的极好方法.
First off, System.XML provides some excellent ways to work with XML.
我假设您将 XML 加载到 XMLDocument 中,这样做允许您使用 XPath 选择器,或者只是遍历 DOM.
I'm assuming you loaded your XML into an XMLDocument, doing so allows you to use XPath Selectors, or just walk through the DOM.
这样的事情会使用递归从任何元素回到顶部:
Something like this would walk from whatever element back up to the top using recursion:
public XmlNode WalkToTopNode (XmlNode CurrentNode)
{
if (CurrentNode.ParentNode == null)
return CurrentNode;
else
return WalkToTopNode(CurrentNode.ParentNode);
}
使用递归按 ID 查找节点可以像这样完成(注意,我在文本框中输入了这个,它可能是错误的):
Using recursion to find a node by ID could be done somewhat like this (Note, I typed this in the textbox, it may be wrong):
public XmlNode GetElementById (string id, XmlNode node)
{
if (node.Attributes["id"] != null && node.Attributes["id"].InnerText == id)
{
return node;
}
else
{
foreach (XmlNode childNode in node.Children)
{
return GetElementById(id, childNode);
}
}
return null;
}
但是,如果您在 System.XML 中内置了许多更好的节点遍历方式的情况下使用递归,那么也许是时候重新考虑您的策略了.
However, if you are using recursion when there are so many better node traversal ways built in to System.XML, then perhaps its time to rethink your strategy.
这篇关于xml 文件的递归函数(层次结构数据)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!