我想遍历XML文件中的所有节点并打印它们的名称。这样做最好的方法是什么?我正在使用.NET 2.0。
XmlDocument doc = new XmlDocument();
doc.Load("sample.xml");
XmlElement root = doc.DocumentElement;
XmlNodeList nodes = root.SelectNodes("some_node"); // You can also use XPath here
foreach (XmlNode node in nodes)
{
// use node variable here for your beeds
}
我认为最快、最简单的方法是使用一个XmlReader,这不需要任何递归和最小的内存占用。
以下是一个简单的例子,为了紧凑起见,我只是使用了一个简单的字符串,当然你也可以使用来自文件的流等等。
string xml = @"
<parent>
<child>
<nested />
</child>
<child>
<other>
</other>
</child>
</parent>
";
XmlReader rdr = XmlReader.Create(new System.IO.StringReader(xml));
while (rdr.Read())
{
if (rdr.NodeType == XmlNodeType.Element)
{
Console.WriteLine(rdr.LocalName);
}
}
以上代码的结果将会是:parent
child
nested
child
other
XML文档中的所有元素列表。
这是我为自己快速写的:
public static class XmlDocumentExtensions
{
public static void IterateThroughAllNodes(
this XmlDocument doc,
Action<XmlNode> elementVisitor)
{
if (doc != null && elementVisitor != null)
{
foreach (XmlNode node in doc.ChildNodes)
{
doIterateNode(node, elementVisitor);
}
}
}
private static void doIterateNode(
XmlNode node,
Action<XmlNode> elementVisitor)
{
elementVisitor(node);
foreach (XmlNode childNode in node.ChildNodes)
{
doIterateNode(childNode, elementVisitor);
}
}
}
为了使用它,我使用了类似以下的方法:
var doc = new XmlDocument();
doc.Load(somePath);
doc.IterateThroughAllNodes(
delegate(XmlNode node)
{
// ...Do something with the node...
});
也许它能帮助某些人。
XDocument xdoc = XDocument.Load("input.xml");
foreach (XElement element in xdoc.Descendants())
{
Console.WriteLine(element.Name);
}
XDocument
而不是XmlDocument
。参见:https://dev59.com/Z3I_5IYBdhLWcg3wEOvq(甚至比这里的问题还要老)。 - Martin Schneider一种递归算法,用于解析 XmlDocument
以下是一个示例 - 递归读取xml文档并使用正则表达式获取内容
这里是另一个递归示例 - http://www.java2s.com/Tutorial/CSharp/0540__XML/LoopThroughXmlDocumentRecursively.html