简体   繁体   English

遍历维护层次结构级别的xml文件

[英]iterating through an xml file maintaining hierarchy levels

i am trying to write a function to iterate my xml file - then use the data found to produce my tree diagram again in dotnetcharting. 我试图编写一个函数来迭代我的xml文件-然后使用发现的数据在dotnetcharting中再次生成我的树形图。

For example, if i have the following (terrible, but just made up!)xml file 例如,如果我有以下(可怕的,但是刚刚组成的)xml文件

<root>
    <Player>
        <firstname/>
        <lastname/>
     </Player>

     <Team>
         <Name/>
          <Country>
              <League>
              </League>
         </Country
     </Team>
</Root>

then the idea is that i would have a tree diagram where i would have my root node, then stemming from this i would have player and team. 那么我的想法是,我将拥有一个树形图,其中将有我的根节点,然后基于此,我将拥有球员和团队。 Then each of the subnodes for each, until eventually the last nodes would be the data. 然后,每个子节点的每个,直到最终最后一个节点将是数据。

  XmlReader rdr = XmlReader.Create(new System.IO.StringReader(xml));
  while (rdr.Read())
  {
    if (rdr.NodeType == XmlNodeType.Element)
    {
      Console.WriteLine(rdr.LocalName);
    }
  }

I know i can read the xml file like this, but i have no way of maintaining any form of heirarchy so i cant tell dotnetcharting whats a parent node of what? 我知道我可以像这样读取xml文件,但是我无法保持任何形式的继承关系,因此我无法告诉dotnetcharting什么是父节点?

Any help? 有什么帮助吗?

I would use recursion for this. 我会为此使用递归。 Personally I would have a function that returns a TreeNode and if the current node contain child element nodes then calls itself such as: 就我个人而言,我将有一个返回TreeNode的函数,如果当前节点包含子元素节点,则将其自身调用,例如:

static class XmlProcessor
{

    public static TreeNode ProcessXml(XmlReader reader)
    {
        // Move to first element
        while(reader.Read() && reader.NodeType != XmlNodeType.Element){}
        return ParseNode(reader);

    }

    private static TreeNode ParseNode(XmlReader reader)
    {
        if (reader.NodeType == XmlNodeType.Text) return new TreeNode(reader.Value);
        if (reader.IsEmptyElement) return new TreeNode(reader.Name);

        TreeNode current = new TreeNode(reader.LocalName);
        while (reader.Read())
        {
            if (reader.NodeType == XmlNodeType.Element)
            {
                current.Nodes.Add(ParseNode(reader));
            }
            else if (reader.NodeType == XmlNodeType.EndElement)
            {
                return current;
            }
        }
        return current;
    }

}

This could be called from the application using: 可以使用以下命令从应用程序中调用:

TreeNode processedNodes = null;
using (XmlReader reader = XmlReader.Create(new System.IO.StringReader(xml))){
  processedNodes = XmlProcessor.ProcessXml(reader);
}

The using block ensures that the XmlReader is closed and disposed correctly once it falls out of scope. using块可确保XmlReader在超出范围后被关闭并正确处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM