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

I have an XML String:

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

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

+7
source share
2 answers

Despite publishing invalid XML (without root node), an easy way to iterate through <FieldRef> Elements should 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 smoother interface is provided by LINQ to XML, maybe it would be easier to use this if it is available within the framework of the .NET platform that you are aiming for? Then the code will look like this:

 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); 
+9
source

try the following:

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

All Articles