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を使用できません.