简体   繁体   English

在C#中发现XML子节点

[英]Discovering XML Childnodes in C#

I need to take in XML with common parent nodes but with varying child nodes. 我需要使用具有公共父节点但具有不同子节点的XML。 Once I get it, I need to grab the tag names of the child nodes and use those names as headers. 一旦获得它,就需要获取子节点的标签名称,并将这些名称用作标题。 In the following example, all incoming XML will be wrapped as follows: 在以下示例中,所有传入的XML都将按以下方式包装:

<customers>
    <customer>
       ...varying child nodes that do not have child nodes themselves
    </customer>
</customers>

I have found that this works: 我发现这可行:

List<string> headerList = new List<string>();
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(someXML);

XmlNodeList xnl = xmlDoc.SelectNodes("customers/customer");

foreach (XmlNode xn in xnl)
{
    for (int x = 0; x < xn.ChildNodes.Count; x++)
    {
        headerList.Add(xn.ChildNodes[x].Name.ToString());
    }
}

Is there a better way to do this? 有一个更好的方法吗?

Thanks in advance. 提前致谢。

This should do the trick; 这应该可以解决问题;

XDocument doc = XDocument.Load(someXML);
var headerList = doc.Descendants("customer").Elements().Select(x => x.Name);

Not necessarily "better", but it's a bit more concise I guess. 不一定“更好”,但我想它要更简洁一些。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM