如何在C#中使用XMLREADER从XML字符串中读取特定元素

Wal*_*eed 8 c# xml

我有XML字符串:

   <GroupBy Collapse=\"TRUE\" GroupLimit=\"30\">
      <FieldRef Name=\"Department\" />
   </GroupBy>
   <OrderBy>
      <FieldRef Name=\"Width\" />
   </OrderBy>
Run Code Online (Sandbox Code Playgroud)

我是C#的新手.我试图读取两个元素的FieldRef元素的Name属性,但我不能.我用过XMLElement,有没有办法选择这两个值?

Jam*_*ler 10

尽管发布了无效的XML(没有根节点),但是迭代<FieldRef>元素的简单方法是使用以下XmlReader.ReadToFollowing方法:

//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");
}
Run Code Online (Sandbox Code Playgroud)

当然,LINQ to XML提供了一个更灵活,更流畅的界面,如果在你所针对的.NET框架中可用的话,它可能会更容易使用吗?代码然后变成:

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);
Run Code Online (Sandbox Code Playgroud)