我怎样才能读取XML字符串中使用的XmlReader在C#中的特定元素 [英] How can I read specific elements from XML string using XMLREADER in C#

查看:280
本文介绍了我怎样才能读取XML字符串中使用的XmlReader在C#中的特定元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有XML字符串:

   <GroupBy Collapse=\"TRUE\" GroupLimit=\"30\">
      <FieldRef Name=\"Department\" />
   </GroupBy>
   <OrderBy>
      <FieldRef Name=\"Width\" />
   </OrderBy>



我在C#中新。我试图读取两个元素FieldRef元素的名称属性,但是我不能。我用XMLELEMENT,有没有什么办法来接这两个值?

I am new in C#. I tried to read the Name attribute of the FieldRef element for both elements but I could not. I used XMLElement , is there any way to pick these two values?

推荐答案

尽管无效的XML(无根节点)的发布FieldRef>,一个简单的方法,通过在<迭代;元素是使用 XmlReader.ReadToFollowing 方法:

Despite the posting of invalid XML (no root node), an easy way to iterate through the <FieldRef> elements is to use the XmlReader.ReadToFollowing method:

//Keep reading until there are no more FieldRef elements
while (reader.ReadToFollowing("FieldRef"))
{
    //Extract the value of the Name attribute
    string value = reader.GetAttribute("Name");
}



当然更灵活和流畅接口由LINQ提供到XML中,也许它会更容易使用,如果在.NET框架中提供您的目标?然后,代码变成:

Of course a more flexible and fluent interface is provided by LINQ to XML, perhaps it would be easier to use that if available within the .NET framework you are targeting? The code then becomes:

using System.Xml.Linq;

//Reference to your document
XDocument doc = {document};

/*The collection will contain the attribute values (will only work if the elements
 are descendants and are not direct children of the root element*/
IEnumerable<string> names = doc.Root.Descendants("FieldRef").Select(e => e.Attribute("Name").Value);

这篇关于我怎样才能读取XML字符串中使用的XmlReader在C#中的特定元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆