简体   繁体   English

如何从C#中具有相同节点名称的XML读取

[英]How to read from XML that has same node names in C#

I have an XML document that looks like that: 我有一个看起来像这样的XML文档:

<?xml version="1.0" encoding="UTF-8"?>
<teryt>
<catalog name="TERC" type="all" date="2015-01-01">
<row>
<col name="WOJ">02</col>
<col name="POW"/>
<col name="GMI"/>
<col name="RODZ"/>
<col name="NAZWA">DOLNOŚLĄSKIE</col>
<col name="NAZDOD">województwo</col>
<col name="STAN_NA">2015-01-01</col>
</row>
...
</row>
</catalog>
</teryt>

I have a code that works, but reads only the first col of every row : 我有一个有效的代码,但仅读取每的第一个col

System.Xml.XmlDocument rssDocument = new System.Xml.XmlDocument();
            rssDocument.Load("TERC.xml");

            System.Xml.XmlNodeList rssItems = rssDocument.SelectNodes("teryt/catalog/row");

            for (int i = 0; i < rssItems.Count; i++)
            {
                System.Xml.XmlNode rssNode;

                rssNode = rssItems.Item(i).SelectSingleNode("col");

                if (rssNode != null)
                {
                    Console.WriteLine(rssNode.InnerText);
                }
                else
                {
                    Console.WriteLine("");
                }
            } 

What do I have to do, if I want to read InnerText from every col in all rows ? 如果我想从所有行的每个中读取InnerText ,该怎么办?

foreach (var row in rssDocument.SelectNodes("teryt/catalog/row"))
{    
    foreach (var col in row.SelectNodes("col"))
    {             
        Console.WriteLine(col.InnerText);    
    }
}

I didn't test this. 我没有测试。 This is to give you an idea of the solution. 这是给您解决方案的想法。 You are only selecting one col from every row because SelectNodes("col") does not give you the nodes inside "col". 您仅从每一行中选择一个col,因为SelectNodes(“ col”)不会为您提供“ col”内的节点。 It gives you the nodes named "col". 它为您提供了名为“ col”的节点。

Change 更改

rssNode = rssItems.Item(i).SelectSingleNode("col");

TO

XmlNodeList list = rssItems.Item(i).SelectNodes("col");

foreach(XmlNode node in list)
{
    Console.WriteLine(node .InnerText);
}

The name of the method explain what is doing: SelectSingleNode . 方法的名称说明了正在执行的操作: SelectSingleNode Selects a single node with this name. 选择具有此名称的单个节点。 You need to select all nodes using SelectNodes method 您需要使用SelectNodes方法选择所有节点

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

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