微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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();
                }
            }
        }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。