c# GetElementsByTagName then read the inner tags values how

MonsterMMORPG picture MonsterMMORPG · Dec 16, 2012 · Viewed 13.9k times · Source

this below is example 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

Answer

Mir picture Mir · Dec 16, 2012

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;
}