2

下面是示例 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>

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

       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

4

2 回答 2

7

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

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;
}
于 2012-12-16T16:41:58.077 回答
6

使用 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();
于 2012-12-16T16:50:42.357 回答