Search code examples
c#wpfxmltagsgetelementsbytagname

c# GetElementsByTagName then read the inner tags values how


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


Solution

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

    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();