c# – 使用XmlReader类使用相同名称的元素解析XML

我正在重写一些使用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.

解决方法:

以下似乎有效: –

        StringBuilder xml = new StringBuilder();

        xml.Append("<items>");
        xml.Append("<item id=\"1\" desc=\"one\">");
        xml.Append("<itembody id=\"10\"/>");
        xml.Append("</item>");
        xml.Append("<item id=\"2\" desc=\"two\">");
        xml.Append("<itembody id=\"20\"/>");
        xml.Append("</item>");
        xml.Append("<item id=\"3\" desc=\"three\">");
        xml.Append("<itembody id=\"30\"/>");
        xml.Append("</item>");
        xml.Append("</items>");

        using (XmlTextReader tr = new XmlTextReader(new StringReader(xml.ToString())))
        {
            bool canRead = tr.Read();
            while (canRead)
            {
                if ((tr.Name == "item") && tr.IsstartElement())
                {
                    Console.WriteLine(tr.GetAttribute("id"));
                    Console.WriteLine(tr.GetAttribute("desc"));
                    string outerxml = tr.ReadOuterXml();
                    Console.WriteLine(outerxml);

                    canRead = (outerxml != string.Empty);
                }
                else
                {
                    canRead = tr.Read();
                }
            }
        }

相关文章

php输出xml格式字符串
J2ME Mobile 3D入门教程系列文章之一
XML轻松学习手册
XML入门的常见问题(一)
XML入门的常见问题(三)
XML轻松学习手册(2)XML概念