我正在重写一些使用 XmlDocument 来解析一些 XML 的代码。我想改用 XmlReader 来查看是否可以获得一些性能改进。XML 的结构如下所示:
<items>
<item id="1" desc="one">
<itemBody date="2012-11-12" />
</item>
<item id="2" desc="two">
<itemBody date="2012-11-13" />
</item>
<item id="3" desc="three">
<itemBody date="2012-11-14" />
</item>
<item id="4" desc="four">
<itemBody date="2012-11-15" />
</item>
</items>
基本上,我需要遍历所有<item>
元素。就像我说的,旧代码是这样工作的:
XmlDocument document = new XmlDocument();
// load XML into XmlDocument
document.LoadXml(xml);
// use xpath to split into individual item
string xPath = @"items/item";
XmlNodeList nodeList = document.SelectNodes(xPath);
// loop through each item
for (int nodeIndex = 0; nodeIndex < nodeList.Count; nodeIndex++)
{
// do something with the XmlNode
nodeList[nodeIndex];
}
这很好用,但我认为使用 XmlReader 会更快。所以我写了这个:
XmlReader xmlReader = XmlReader.Create(new StringReader(xml));
while (xmlReader.Read())
{
if (xmlReader.Name.Equals("item") && (xmlReader.NodeType == XmlNodeType.Element))
{
string id = xmlReader.GetAttribute("id");
string desc = xmlReader.GetAttribute("desc");
string elementXml = xmlReader.ReadOuterXml();
}
}
但是,此代码仅读取第一个<item>
元素。ReadOuterXml() 正在打破循环。有人知道如何解决这个问题吗?或者这种类型的解析无法使用 XmlReader 进行?我必须使用 .NET 版本 2 来做到这一点 :( 所以我不能使用 LINQ。