简体   繁体   English

如何从没有属性的 XML 文件中获取节点并放入字符串列表

[英]How to get nodes from XML file without its attribute and put to a List of string

I would like to display the tag names of child nodes without its attributes.我想显示没有属性的子节点的标签名称。 Then those tag names (nodes) should be put in a List of string.然后这些标签名称(节点)应该放在一个字符串List中。 Here's example of my XML file:这是我的 XML 文件的示例:

<?xml version="1.0" encoding="UTF-8"?>
<ROOT>
    <CAR>
        <ID>21</ID>
        <MANUFACTURER>Ford</MANUFACTURER>
        <MODEL>Fiesta</MODEL>
    </CAR>
    <CAR>
        <ID>22</ID>
        <MANUFACTURER>Peugeot</MANUFACTURER>
        <MODEL>508</MODEL>
    </CAR>
</ROOT>

So, the effect I want to get in a console output is shown below:所以,我想在控制台 output 中得到的效果如下图所示:

ID
MANUFACTURER
MODEL

Then I would like to store that ID, MANUFACTURER and MODEL tag names in a List of strings.然后我想将该 ID、MANUFACTURER 和 MODEL 标记名称存储在字符串List中。

This is the code that I tried so far:这是我到目前为止尝试的代码:

            XmlDocument xmlDocument = new XmlDocument();
            xmlDocument.PreserveWhitespace = true;
            try
            {
                xmlDocument.Load("XMLFile.xml");
            }
            catch (FileNotFoundException ex)
            {
                Console.WriteLine(ex);
            }

            Console.WriteLine(xmlDocument.OuterXml);

            XmlNodeList nodeList = xmlDocument.SelectNodes("ROOT/CAR");
            foreach(XmlNode node in nodeList)
            {
                Console.WriteLine(node.ChildNodes);
                xmlNodes.Add(node.ChildNodes.ToString());
            }

The problem is that it's not displaying the way I want to.问题是它没有显示我想要的方式。 As a result I only get two System.Xml.XmlChildNodes which seems to be corresponding to two <CAR> nodes, instead of its three child nodes, such as ID, MANUFACTURER and MODEL.结果,我只得到了两个System.Xml.XmlChildNodes ,它们似乎对应于两个<CAR>节点,而不是它的三个子节点,例如 ID、MANUFACTURER 和 MODEL。

System.Xml.XmlChildNodes
System.Xml.XmlChildNodes

Adding items to a List basically adds the same thing as shown above.将项目添加到列表基本上添加了与上面所示相同的内容。

What am I doing wrong?我究竟做错了什么?

You could loop through for children nodes:您可以循环遍历子节点:

1- You can define xmlNodes like a HashSet to avoid multiple tags like: 1-您可以像HashSet一样定义xmlNodes以避免多个标签,例如:

HashSet<string> xmlNodes = new HashSet<string>();

2 - Change little the code like: 2 - 改变一点代码,如:

....
XmlNodeList nodeList = xmlDocument.SelectNodes("ROOT/CAR");
foreach (XmlNode node in nodeList)
{
    foreach(XmlNode element in node.ChildNodes)
    {
        if (element.NodeType == XmlNodeType.Element)
            xmlNodes.Add(element.Name);
    }
}

Demo演示

Console.WriteLine(string.Join(", ", xmlNodes));

Result结果

ID, MANUFACTURER, MODEL

I hope you find this helpful.我希望你觉得这有帮助。

If you have to use XmlDocument, then you can -如果您必须使用 XmlDocument,那么您可以 -

List<string> elements = new List<string>();
XmlNodeList CarNodes = xml.SelectNodes("Root/Car");
foreach(XmlNode c in CarNodes)
{
    foreach(XmlNode n in c.ChildNodes)
    {
        if (!elements.Contains(n.Name))
        {
            elements.Add(n.Name);
        }
    }
}

But I find XDocument to be much simpler and better readability.但我发现XDocument更简单,可读性更好。

XDocument xdoc = XDocument.Parse(yourXmlString);
List<string> elements = xdoc.Descendants("Car")
                            .DescendantNodes().OfType<XElement>()
                            .Select(x => x.Name).Distinct().ToList();

And thats all you'll need.这就是你所需要的。 Easy to read as well, get all the descendants of "Car" Node and get all distinct names of XElements within it.也易于阅读,获取“汽车”节点的所有后代并获取其中所有不同的 XElement 名称。

Another way to do it -另一种方法-

List<string> elements = xdoc.Descendants("Car").First()
                            .DescendantNodes().OfType<XElement>()
                            .Select(x => x.Name).ToList();

In this case I have removed the "distinct" and rather got just the first Car node ONLY .在这种情况下,我删除了“distinct”,而只得到了第一个 Car 节点ONLY You can see the difference - if by any case some other Car node has an extra element, you'll miss getting that information by doing it this way.您可以看到差异 - 如果在任何情况下某个其他 Car 节点有一个额外的元素,您将无法通过这种方式获取该信息。

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

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