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

时间:2012-01-17 01:59:11

标签: c# xml

我有XML String:

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

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

2 个答案:

答案 0 :(得分:10)

尽管发布了无效的XML(没有根节点),但是通过&lt; FieldRef&gt;迭代的简单方法元素是使用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");
}

当然,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);

答案 1 :(得分:-1)

试试这个:

    string xml = "<GroupBy Collapse=\"TRUE\" GroupLimit=\"30\"><FieldRef Name=\"Department\" /></GroupBy><OrderBy> <FieldRef Name=\"Width\" /></OrderBy>";
    xml = "<root>" + xml + "</root>";
    XmlDocument doc = new XmlDocument();
    doc.LoadXml(xml);
    foreach (XmlNode node in doc.GetElementsByTagName("FieldRef"))
        Console.WriteLine(node.Attributes["Name"].Value);