简体   繁体   English

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

[英]How can I read specific elements from XML string using XMLREADER in C#

I have XML String: 我有XML字符串:

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

I am new in C#. 我是C#的新手。 I tried to read the Name attribute of the FieldRef element for both elements but I could not. 我试图读取两个元素的FieldRef元素的Name属性,但我不能。 I used XMLElement , is there any way to pick these two values? 我用过XMLElement,有没有办法选择这两个值?

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

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? 当然,LINQ to XML提供了一个更灵活,更流畅的界面,如果在你所针对的.NET框架中可用的话,它可能会更容易使用吗? 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);

try this: 试试这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM