使用C#在XML树中获取不同的属性值和节点值

时间:2018-03-02 12:57:02

标签: c# xml

我有以下XML

<?xml version="1.0" encoding="UTF-8"?>
<configuration-template name="TEMPLATE_NAME" version="v1.0">
    <configuration-item name="mx.reporting.setup.SqlTable" object-id="CM.353">
        <instances>
            <instance label="RTA_INSTANCE.REP,Client">
                <instance-key property="label" with-quotes="true">RTA_INSTANCE.REP</instance-key>
                <instance-key property="murex">0</instance-key>
            </instance>
        </instances>
    </configuration-item>
    <configuration-item name="mx.reporting.datamart.BatchOfFeeders" object-id="CM.418">
        <instances>
            <instance label="RBA_INSTANCE2">
                <instance-key property="label" with-quotes="true">RBA_INSTANCE2</instance-key>
            </instance>
        </instances>
    </configuration-item>
</configuration-template>

我想要的是取出配置模板名称,即TEMPLATE_NAME 并为每个配置项列出了object-id和Instance键

所以在这种情况下它将是

TEMPLATE_NAME CM.353 RTA_INSTANCE.REP
TEMPLATE_NAME CM.418 RBA_INSTANCE2

我设法从指定目录打开xml,并获取一些值

但不知道如何正确浏览XML

using System;
using System.IO;
using System.Xml;
using System.IO.Compression;

public class Sample
{
    public static void Main()
    {
        //Create the XmlDocument.
        XmlDocument doc = new XmlDocument();
        string[] dirs = Directory.GetFiles(@"C:\TFS\SUP\System", "*.xml");
        string[] arr = new string[] {"Name1.xml", "Name2.xml"};

        Console.WriteLine(arr.Length);
        XmlNodeList elemList = doc.GetElementsByTagName("configuration-item");
        XmlNodeList elemList2 = doc.GetElementsByTagName("instance-key");
        XmlNodeList elemList3 = doc.GetElementsByTagName("configuration-template");

        for (int b = 0; b < arr.Length; b++)
        {
            doc.Load(arr[b]);

            for (int i = 0; i < elemList.Count; i++)
            {
                Console.WriteLine(elemList3[i].Attributes["name"].Value);
                Console.WriteLine(elemList2[i].InnerXml);
                Console.WriteLine(elemList[i].Attributes["object-id"].Value);
                Console.ReadLine();
            }

        }


    }
}

0 个答案:

没有答案