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

10

我有一个XML字符串:

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

我是C#的新手。我尝试读取FieldRef元素的Name属性,但无法做到。我使用了XMLElement,是否有任何方法可以获取这两个值?


4
XML的其余部分是什么?有效的XML必须有一个根节点。 - wsanville
2个回答

12

尽管发布了无效的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");
}

当然,如果您的.NET框架中提供了LINQ to XML,那么它会提供更灵活和流畅的界面,也许使用它会更容易?代码如下:

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

我注意到FieldRef元素并不总是包含在同一个父节点中,后代将考虑到这一点,并提取它,无论它嵌套在哪个元素中。如果您想使用LINQ to XML获取父元素,可以尝试以下代码:IEnumerable<KeyValuePair<XElement, string>> pairings = doc.Root.Descendants("FieldRef").Select(e => new KeyValuePair<XElement, string>(e.Parent, e.Attribute("Name").Value)); - James Shuttler
我有一个字符串而不是文件,我该如何定义doc变量?我看到它的类型是XDocument,我该如何将我的字符串链接到doc? - Waleed
@Waleed 对不起,我没有意识到这一点,只要字符串是有效的 XML(你发布的 XML 不是,它需要一个根节点),那么你可以使用 XDocument doc = XDocument.Parse({xml}); 静态方法,该方法在 MSDN 上有文档说明。 - James Shuttler
那太好了,我已经按配对方式获取了所有信息,但是我该如何选择特定的 xelement 并将其存储到字符串中呢?我知道我应该通过循环来获取值,但是怎么做呢?感谢您在这最后一步中的帮助。 - Waleed
在我的情况下,当 XML 标签名称包含“:”冒号时,该方法会变得疯狂,抛出“未声明的前缀”错误并关闭应用程序。这纯粹是疯狂!微软做错了!例如:reader.ReadToFollowing("mnc:MUX")。 - TomeeNS
显示剩余4条评论

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

问题是,这个字符串不固定,有时它不包含GroupBy元素,有时它包含OrderBy元素。我需要选取FieldRef并知道它属于哪个根元素。 - Waleed

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接