C# - 将XML转换为具有不同结构的新XML

时间:2018-02-20 09:36:28

标签: c# xml recursion serialization xml-parsing

我有一个XML文件,它有节点和子节点,某种类型的树视图。我想阅读这些元素并提取内容,将它们写入一个新的XML,并使用一个带有较轻树层次结构的新模式。

在我的代码中,我解析XML文件并读取节点和子节点,但我只能将节点打印到控制台。我无法弄清楚如何使用方法的递归将节点写入XML结构中的新XML。 我是XML的菜鸟?我错过了什么吗?

XML示例

<node clasification= some data about the node">
  <dimension = some sort of info layer>
  <children>
      <node clasification= some data about the node">
         <dimension = some sort of info layer>
         <children>
                  <node clasification= some data about the node">
                    <dimension = some sort of info layer>
                    </children>
                  </node>
                  <node clasification= some data about the node">
                    <dimension = some sort of info layer>
                    </children>
                  </node>
         </children>
      </node>
  </children>
</node>

我的代码基于此:

static void Main(string[] args)
{
    XmlDocument doc = new XmlDocument();
    doc.Load("../../Employees.xml");
    XmlNode root = doc.SelectSingleNode("*"); 
    ReadXML(root);
}

private static void ReadXML(XmlNode root)
{
    if (root is XmlElement)
    {
        DoWork(root);

        if (root.HasChildNodes)
            ReadXML(root.FirstChild);
        if (root.NextSibling != null)
            ReadXML(root.NextSibling);
    }
    else if (root is XmlText)
    {}
    else if (root is XmlComment)
    {}
}

private static void DoWork(XmlNode node)
{
    if (node.Attributes["Code"] != null)
        if(node.Name == "project" && node.Attributes["Code"].Value == "Orlando")
            Console.WriteLine(node.ParentNode.ParentNode.Attributes["Name"].Value);
}

请帮助:)

1 个答案:

答案 0 :(得分:0)

我找到了一种以递归方式完成它的方法。 我无法分享最终的代码,因为它是在一个无法访问互联网的封闭网络上,但基本上,我在readxml的开头创建了一个新节点,并在最后返回它,所以我不能将子对象发送给它递归...

类似的东西(伪代码)

   private static XmlNode ReadXML(XmlNode root)
    {
      XmlNode tmp = new XmlNode;
        // pupulate the node attributes
        tmp = DoWork(root);

foreach (xmlnode childnode in node.childnodes)
{
     if (check if you want this node)
{
       XmlNodeList tmplist = childnode.childnodes;
            if (tmplist.HasChildNodes)
               {
                 tmp.newnode = new ChildNode[tmplist.count];
                 for (i=0;i<tmpnode.count;i++)
                   {
                     tmp.tmpnode[i] = ReadXML(tmplist.item(i));
                   }
                        }
        else 
        {}
    }
}

现在工作正常