如何在xml中获取子节点的名称

本文关键字:子节点 获取 xml | 更新日期: 2023-09-27 18:28:05

我的XML看起来像这个

<Location>
    <AChau>
        <ACity>
          <EHouse/>
          <FHouse/>
          <GHouse/>
        </ACity>
        <BCity>
          <HHouse/>
          <IHouse/>
          <JHouse/>
          <KHouse/>
        </BCity>
    </AChau>
</Location>

我找到了很多方法,我在这里找到了最接近的答案

在silverlight 中获取xml中的所有节点名称

但它读取了所有的后代,我需要的是从"位置"获得"AChau"

从"Location/AChau"获取"ACity"BCity"

从"Location/AChau/ACity"获取"EHouse"FHouse"answers"GHouse"

如何只读子节点?

如何在xml中获取子节点的名称

假设您有一个XElement,您可以使用以下代码提取其子级的名称数组:

string[] names = xElem.Elements().Select(e => e.Name.LocalName).ToArray();

例如,此代码与XML:

public static MyXExtensions 
{
    public static string[] ChildrenNames(this XElement xElem)
    {
        return xElem.Elements().Select(e => e.Name.LocalName).ToArray();
    }
}
string[] names1 = xDoc.Root.ChildrenNames();
string[] names2 = xDoc.Root.Element("AChau").ChildrenNames();
string[] names3 = xDoc.XPathSelectElement("Location/AChau/ACity").ChildrenNames();

将分别返回以下数组:

["AChau"]
["ACity", "BCity"]
["EHouse", "FHouse", "GHouse"]

如果您使用XElement从xml获取数据,那么您只需要FirstNode属性和Elements方法。

FirstNode返回元素的第一个子节点,Elements返回元素的所有直接子节点。

如果您总是想要根下的第一个节点名:

string xml = @"<Location>
              <AChau>
                <ACity>
                  <EHouse/>
                  <FHouse/>
                  <GHouse/>
                </ACity>
                <BCity>
                  <HHouse/>
                  <IHouse/>
                  <JHouse/>
                  <KHouse/>
                </BCity>
              </AChau>
            </Location>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
XmlNode root = doc.DocumentElement;
XmlNode first = root.FirstChild;

试试这个xml linq

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string xml = 
                "<Location>" +
                    "<AChau>" +
                        "<ACity>" +
                          "<EHouse/>" +
                          "<FHouse/>" +
                          "<GHouse/>" +
                        "</ACity>" +
                        "<BCity>" +
                          "<HHouse/>" +
                          "<IHouse/>" +
                          "<JHouse/>" +
                          "<KHouse/>" +
                        "</BCity>" +
                    "</AChau>" +
                "</Location>";
            XElement location = XElement.Parse(xml);
            var results = location.Descendants("AChau").Elements().Select(x => new
            {
                city = x.Name.LocalName,
                houses = string.Join(",",x.Elements().Select(y => y.Name.LocalName).ToArray())
            }).ToList();
        }
    }
}
​