wpf c# GetElementsByTagName 然后读取内部标签值如何

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13903218/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 06:37:54  来源:igfitidea点击:

c# GetElementsByTagName then read the inner tags values how

c#wpfxmltagsgetelementsbytagname

提问by MonsterMMORPG

this below is example xml

下面是示例 xml

<DOC>
<DOCNO>WSJ870323-0180</DOCNO>
<HL>Italy's Commercial Vehicle Sales</HL>
<DD>03/23/87</DD>
<DATELINE>TURIN, Italy</DATELINE>
<TEXT>Commercial-vehicle sales in Italy rose 11.4% in February from a year earlier, to 8,848 units, according to provisional figures from the Italian Association of Auto Makers.</TEXT>
</DOC>

<DOC>
<DOCNO>WSJ870323-0180</DOCNO>
<HL>Italy's Commercial Vehicle Sales</HL>
<DD>03/23/87</DD>
<DATELINE>TURIN, Italy</DATELINE>
<TEXT>Commercial-vehicle sales in Italy rose 11.4% in February from a year earlier, to 8,848 units, according to provisional figures from the Italian Association of Auto Makers.</TEXT>
</DOC>

and this below code is not working why ?

下面的代码不起作用,为什么?

       System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
    doc.Load("docs.xml");

    XmlNodeList elemList = doc.GetElementsByTagName("DOC");
    for (int i = 0; i < elemList.Count; i++)
    {
        string docno = elemList[i].Attributes["DOCNO"].ToString();
    } 

C# 4.0 wpf

C# 4.0 wpf

回答by Mir

Use this code, assuming you have a valid root:

使用此代码,假设您有一个有效的根:

XmlNodeList elemList = doc.GetElementsByTagName("DOC");
for (int i = 0; i < elemList.Count; i++)
{
    var elements = elemList[i].SelectNodes("DOCNO");
    if (elements == null || elements.Count == 0) continue;
    var firstElement = elements.Item(0);
    var docno = firstElement.InnerText;
}

回答by L.B

Using Linq To Xml to parse Xml is much more easier. For example,

使用 Linq To Xml 解析 Xml 要容易得多。例如,

var xDoc = XDocument.Load("docs.xml");

var docs = xDoc.Descendants("DOC")
            .Select(x => new{
                DocNo = x.Element("DOCNO").Value,
                Text = x.Element("TEXT").Value
            })
            .ToList();