[英]How to get depth of current XML-node with C# and XMLReader
I tried with Reader.Depth but the function returns completely false numbers. 我尝试使用Reader.Depth,但该函数返回完全错误的数字。 The XML-file is extremely huge, so here´s just a little example:
XML文件非常巨大,因此这里只是一个小例子:
Node1
Node1.2
Node1.2.1
Node1.2.1.1
...........
Node1.2.2
Node2.2
Noce2
You got the idea. 你明白了。
So how can I get the real depth of every node? 那么如何获得每个节点的真实深度? Reader.depth does not work right, it always returns "2", no matter which node I use it on.
Reader.depth不能正常工作,无论我在哪个节点上使用它,它始终返回“ 2”。
Here´s the code snippet: 这是代码段:
while (reader2.Read())
{
if (reader2.NodeType == XmlNodeType.Element)
{
switch (reader2.Name)
{
case "the_node":
the_node = new My_Node();
list_myNodes.Add(the_node);
the_node.howdeep = reader2.Depth;
break;
case "name":
[......]
case "argument":
[......]
}
}
}
Later, I get all the right values, name is right, argument is right, all the others are right... only the depth is wrong 后来,我得到了所有正确的值,名称正确,参数正确,其他所有参数都正确……只是深度是错误的
Did u try using XMLTextReader ? 您是否尝试使用XMLTextReader?
You can find the MSDN documentation here ! 您可以在这里找到MSDN文档!
Additionally see the code snippet from the MSDN documentation below. 另外,请参见下面的MSDN文档中的代码片段。
using System;
using System.IO;
using System.Xml;
public class Sample{
public static void Main(){
// Create the XML fragment to be parsed.
string xmlFrag =
@"<book>
<misc>
<style>paperback</style>
<pages>240</pages>
</misc>
</book>";
// Create the XmlNamespaceManager.
NameTable nt = new NameTable();
XmlNamespaceManager nsmgr = new XmlNamespaceManager(nt);
// Create the XmlParserContext.
XmlParserContext context = new XmlParserContext(null, nsmgr, null, XmlSpace.None);
// Create the reader.
XmlTextReader reader = new XmlTextReader(xmlFrag, XmlNodeType.Element, context);
// Parse the XML and display each node.
while (reader.Read()){
switch (reader.NodeType){
case XmlNodeType.Element:
Console.Write("{0} {1},{2} ", reader.Depth, reader.LineNumber, reader.LinePosition);
Console.WriteLine("<{0}>", reader.Name);
break;
case XmlNodeType.Text:
Console.Write("{0} {1},{2} ", reader.Depth, reader.LineNumber, reader.LinePosition);
Console.WriteLine(" {0}", reader.Value);
break;
case XmlNodeType.EndElement:
Console.Write("{0} {1},{2} ", reader.Depth, reader.LineNumber, reader.LinePosition);
Console.WriteLine("</{0}>", reader.Name);
break;
}
}
// Close the reader.
reader.Close();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.