以下是示例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
答案 0 :(得分:6)
使用此代码,假设您有一个有效的根:
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;
}
答案 1 :(得分: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();