Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

xml

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?

like image 312
Waleed Avatar asked Jan 17 '12 01:01

Waleed


People also ask

How to Read XML element value in c# using XmlReader?

MoveToContent(); var data = reader. ReadElementContentAsString(); Console. WriteLine(data); In the example, we read the value from the simple XML document with XmlReader .

What is Xmlreadersettings?

Specifies a set of features to support on the XmlReader object created by the Create method.


1 Answers

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);
like image 187
James Shuttler Avatar answered Sep 23 '22 22:09

James Shuttler