简体   繁体   中英

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

I have XML String:

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

I am new in C#. I tried to read the Name attribute of the FieldRef element for both elements but I could not. I used XMLElement , is there any way to pick these two values?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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