C#使用XMLReader(?)读取子元素

时间:2018-10-03 14:11:50

标签: c# xml xmlreader

我目前正在努力从子元素中读取子元素。读取具有如下结构的XML的最佳方法是什么:

<network>
<channel type="...">
        <sub1.1>...</sub1.1>
        <sub1.2>...</sub1.2>
        ...
</channel>

<channel type="...">
        <sub1.1>...</sub1.1>
        <sub1.2>...</sub1.2>
        ...
</channel>
...

<group number="...">
        <sub2.1>...</sub2.1>
        <sub2.2>...</sub2.2>
        ...
</group>
...

<group number="...">
        <sub2.1>...</sub2.1>
        <sub2.2>...</sub2.2>
        ...
</group>
...

<gateway id="...">
        <sub3.1>...</sub3.1>
        <sub3.2>...</sub3.2>
        <sub3.3>
                <sub3.3.1>...</sub3.3.1>
        </sub3.3>
        <sub3.4>
                <sub3.4.1>...</sub3.4.1>
        </sub3.4>
...
</gateway>
...
<network>

我想阅读类型,数字,id ...等属性,以及所有子元素和子子元素。我用XMLReader尝试过,但是在获取子子元素等方面却苦苦挣扎...

如果有人可以帮助我找到一种方法,我将非常感激。

1 个答案:

答案 0 :(得分:1)

您可以使用MoveToFirstElementAttribute()MoveToNextAttribute()来获取属性名称(及其值)

string fileName = @"C:\file.xml";

using (XmlTextReader reader = new XmlTextReader(fileName)) //using System.Xml
        {
            while (reader.Read())
            {
                if (reader.NodeType == XmlNodeType.Whitespace || reader.NodeType == XmlNodeType.EndElement) continue;
                Console.WriteLine("\n------------------------------------------------------------------------------");

                string message = $"Position: {reader.LineNumber},{reader.LinePosition}\tNode Type: {reader.NodeType.ToString()}\tDepth: {reader.Depth}\n";
                if (reader.Name.Trim() != "") message += $"Name: {reader.Name}\t";
                if (reader.Value.Trim() != "") message += $"Value: {reader.Value}\t";
                Console.WriteLine(message);

                // Read() method doesn't get into attribute nodes, so check them manually then get them by MoveToFirstElementAttribute() and MoveToNextAttribute() methods
                if (reader.HasAttributes)
                {
                    Console.WriteLine($"\nHas {reader.AttributeCount} Attribute(s):\n");
                    reader.MoveToFirstAttribute();

                    Console.WriteLine($"Attribute Name: {reader.Name}\tValue: {reader.Value}");
                    while (reader.MoveToNextAttribute())
                    {
                        Console.WriteLine($"Attribute Name: {reader.Name}\tValue: {reader.Value}");
                    }
                    reader.MoveToElement();
                }
            }
        }

我使用了 XmlTextReader (这是 XmlReader 的子类),因为它包含行信息。如果您想使用 XmlReader ,则可以将其替换为 XmlTextReader (除了 XmlReader 没有 LineNumber LinePosition 属性)

您还可以通过Depth属性检查元素的“子性”。请记住,Depth从0开始(深度值最远的元素将是 0