-1

I have a XML file which looks like this:

<Create>
  <Test Id="01" Marks="40" Rank="4"/>
  <Test Id="02" Marks="60" Rank="5"/>
  <Test Id="03" Marks="80" Rank="2"/>
</Create>

Now I want to read the attribute values of Id, Marks and Rank.
So what would the corresponding C# code look like to get those attribute values?

zx485
  • 28,498
  • 28
  • 50
  • 59
Goyal
  • 1
  • 3
  • 1
    Hi, Welcome to Stack Overflow. Please update your question to let us know what you have tried already and provide any code that you may have for the problem. You are likely to get a better answer if you include as much detail as you can. – William Patton Mar 27 '17 at 13:51
  • I improved the code formatting, the question and the title. And added a tag. – zx485 Mar 29 '17 at 20:51

1 Answers1

0

You can use a combination of XmlDocument and XPath.

On line 1 the string is converted to escape the quotes. Then the XMLDocument class is instantiated and the method LoadXml is used to load the string. This can be changed to load a file instead by using xml.Load([path to file]).

Once the document is loaded the Test elements can be selected with "Create/Test" xpath. Finally we loop through each of the nodes and output the data required. I've done this in a c# console app and left out the boilerplate.

var xmlString = "<Create><Test Id=\"01\" Marks=\"40\" Rank=\"4\"/><Test Id=\"02\" Marks=\"60\" Rank=\"5\"/><Test Id=\"03\" Marks=\"80\" Rank=\"2\"/></Create>";
var xml = new XmlDocument();
xml.LoadXml(xmlString);
var nodes = xml.SelectNodes("Create/Test");
foreach (XmlNode node in nodes)
{
    Console.WriteLine(string.Format("Id: {0}; Marks: {1}; Rank: {2}", node.Attributes["Id"].Value, node.Attributes["Marks"].Value, node.Attributes["Rank"].Value));
}

W3C schools have an XPath tutorial which can be found here: https://www.w3schools.com/xml/xpath_intro.asp

XMLDocument class documentation can be found here: https://msdn.microsoft.com/en-us/library/system.xml.xmldocument(v=vs.110).aspx

Gun
  • 83
  • 3
  • 7
  • Hi, thanks for your answer.I am able to access the first node using Xmlreader and using Object.Movetonextattribute() function I have even traversed the value of attributes but now I am stuck that how will I move to next node and access other attributes. – Goyal Mar 28 '17 at 15:44
  • have a look at http://stackoverflow.com/questions/2441673/reading-xml-with-xmlreader-in-c-sharp. It has a good example of doing this – Gun Mar 29 '17 at 13:15