Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Read XML in .NET?

Tags:

c#

xml

XML noob here! So I have some xml data:

<DataChunk>     <ResponseChunk>         <errors>             <error code=\"0\">                 Something happened here: Line 1, position 1.             </error>         </errors>     </ResponseChunk> </DataChunk> 

How would I get the a list of "errors" where I can get access to the "error code" and the text description following...? Also, I'm using .net4.0 in c#...thanks!

like image 771
sringer Avatar asked Jan 20 '11 21:01

sringer


People also ask

How do I read XML files?

If all you need to do is view the data in an XML file, you're in luck. Just about every browser can open an XML file. In Chrome, just open a new tab and drag the XML file over. Alternatively, right click on the XML file and hover over "Open with" then click "Chrome".

What is XML reader in asp net?

XmlReader provides forward-only, read-only access to XML data in a document or stream. This class conforms to the W3C Extensible Markup Language (XML) 1.0 (fourth edition) and the Namespaces in XML 1.0 (third edition) recommendations. XmlReader methods let you move through XML data and read the contents of a node.

How read and write data from XML in C#?

The XmlReader, XmlWriter and their derived classes contains methods and properties to read and write XML documents. With the help of the XmlDocument and XmlDataDocument classes, you can read entire document. The Load and Save method of XmlDocument loads a reader or a file and saves document respectively.


1 Answers

Load the XML into an XmlDocument and then use xpath queries to extract the data you need.

For example

XmlDocument doc = new XmlDocument(); doc.LoadXml(xmlstring);  XmlNode errorNode = doc.DocumentElement.SelectSingleNode("/DataChunk/ResponseChunk/Errors/error");  string errorCode = errorNode.Attributes["code"].Value; string errorMessage = errorNode.InnerText; 

If there is potential for the XML having multiple error elements you can use SelectNodes to get an XmlNodeList that contains all elements at that xpath. For example:

XmlDocument doc = new XmlDocument(); doc.LoadXml(xmlstring);  XmlNodeList errorNodes = doc.DocumentElement.SelectNodes("/DataChunk/ResponseChunk/Errors/error");  foreach(XmlNode errorNode in errorNodes) {   string errorCode = errorNode.Attributes["code"].Value;   string errorMessage = errorNode.InnerText; } 

Option 2

If you have a XML schema for the XML you could bind the schema to a class (using the .NET xsd.exe tool). Once you have that you can deserialise the XML into an object and work with it from that object rather than the raw XML. This is an entire subject in itself so if you do have the schema it is worth looking into.

like image 108
MrEyes Avatar answered Sep 24 '22 13:09

MrEyes