从C#中的xml文件读取所有Leaf XML标记 [英] Reading All the Leaf XML Tags from a xml File in C#

查看:179
本文介绍了从C#中的xml文件读取所有Leaf XML标记的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的Xml结构,它来自文件,不知道它有什么

Hi i have the Xml Structure like this coming from a file, no idea what it has

<xml>
<Node>
<child1></child1>
<child2><child2_1></child2_1></child2>
............(more similar structure)
</Node>
<Node>........(similar childs as in first node)</node)

我需要一个不会将整个文档加载到内存中的解决方案,因为它庞大.因此我需要读取任何一个父节点,例如< Node>并获取该节点中的所有子xml标记,从而使输出应为 

I need a solution that will not load the whole document into memory, because its huge. so I need to read any one of the Parent nodes like <Node> and get all the child xml tags in that node lets the the output should like 

<child1> <child2_1>

.....

如您所见,如果节点具有叶子,则将跳过父节点,并将其所有叶子添加到列表中.

As you can see that if a node has leafs the parent will be skipped and all its leafs will be added to the list.

推荐答案

你好,斯里坎特,

Hello Srikanth,

希望这足以帮助您入门:

Hopefully this is enough to get you started:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace XmlTree
{
    class Program
    {
        static void Main(string[] args)
        {
            var doc = GenerateTree(3, 10);

            foreach (XmlNode node in doc.SelectNodes("//*[not(*)]"))
            {
                Console.WriteLine(node.Name);
            }

            Console.Read();
        }

        private static XmlDocument GenerateTree(int d, int b)
        {
            var doc = new XmlDocument();
            XmlNode node = doc.CreateElement("Node");

            for(int depth=0; depth < d; depth++)
            {
                var branch = doc.CreateElement(string.Format("child{0}", depth));

                for(int leaf=0; leaf < b; leaf++)
                {
                    branch.AppendChild(doc.CreateElement(string.Format("child{0}_{1}", depth, leaf)));
                }

                node.AppendChild(branch);
            }

            doc.AppendChild(node);

            return doc;
        }
    }
}


这篇关于从C#中的xml文件读取所有Leaf XML标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆