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

前端 未结 2 883
-上瘾入骨i
-上瘾入骨i 2021-01-17 17:27

I have XML String:

   
      
   
   <         


        
相关标签:
2条回答
  • 2021-01-17 17:51

    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);
    
    0 讨论(0)
  • 2021-01-17 18:03

    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:

    //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? 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);
    
    0 讨论(0)
提交回复
热议问题