【问题标题】:How can I read specific elements from XML string using XMLREADER in C#如何在 C# 中使用 XMLREADER 从 XML 字符串中读取特定元素
【发布时间】:2012-02-11 21:55:18
【问题描述】:

我有 XML 字符串:

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

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

【问题讨论】:

  • XML 的其余部分是什么?有效的 XML 必须有一个根节点。

标签: c# xml


【解决方案1】:

尽管发布了无效的 XML(无根节点),但迭代 元素的一种简单方法是使用 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);

【讨论】:

  • 问题是,这个字符串不是固定的,有时它不包含GroupBy元素,有时它包含OrderBy元素。我需要选择 FieldRef,我应该知道它属于哪个根元素。
  • 我注意到 FieldRef 元素并不总是包含在同一个父节点中,后代将对此进行解释并提取它,而不管它嵌套在哪个元素中。如果您还希望使用 LINQ to XML 获取父元素,请尝试以下操作:IEnumerable&lt;KeyValuePair&lt;XElement, string&gt;&gt; pairings = doc.Root.Descendants("FieldRef").Select(e =&gt; new KeyValuePair&lt;XElement, string&gt;(e.Parent, e.Attribute("Name").Value));
  • 我有一个字符串而不是一个文件,我将如何定义 doc 变量?当我看到它的 XDocument 类型时,如何将我的字符串链接到文档?
  • @Waleed 对不起,我没有意识到,只要字符串是有效的 XML(您发布的 XML 不是,它需要一个根节点),那么您可以使用 XDocument doc = XDocument.Parse({xml}); 静态方法,记录在MSDN
  • 很抱歉,但我有一个错误:'System.Collections.Generic.IEnumerable' 不包含'Select' 的定义并且没有扩展方法可以找到接受“System.Collections.Generic.IEnumerable”类型的第一个参数的“Select”(您是否缺少 using 指令或程序集引用?)我之前是否应该将 e 定义为 XMLElement ?我应该赋予它什么价值?
【解决方案2】:

试试这个:

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

【讨论】:

  • 问题是,这个字符串不是固定的,有时它不包含GroupBy元素,有时它包含OrderBy元素。我需要选择 FieldRef,我应该知道它属于哪个根元素。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-12-03
  • 2013-09-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-27
  • 2016-03-23
相关资源
最近更新 更多