Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read a XML (from a string) and get some fields - Problems reading XML

I have this XML (stored in a C# string called myXML)

<?xml version="1.0" encoding="utf-16"?> <myDataz xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">   <listS>     <sog>       <field1>123</field1>       <field2>a</field2>       <field3>b</field3>     </sog>     <sog>       <field1>456</field1>       <field2>c</field2>       <field3>d</field3>     </sog>   </listS> </myDataz> 

and I'd like to browse all <sog> elements. For each of them, I'd like to print the child <field1>.

So this is my code :

XmlDocument xmlDoc = new XmlDocument(); string myXML = "<?xml version=\"1.0\" encoding=\"utf-16\"?><myDataz xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"><listS><sog><field1>123</field1><field2>a</field2><field3>b</field3></sog><sog><field1>456</field1><field2>c</field2><field3>d</field3></sog></listS></myDataz>" xmlDoc.Load(myXML); XmlNodeList parentNode = xmlDoc.GetElementsByTagName("listS"); foreach (XmlNode childrenNode in parentNode) {     HttpContext.Current.Response.Write(childrenNode.SelectSingleNode("//field1").Value); } 

but seems I can't read a string as XML? I get System.ArgumentException

like image 281
markzzz Avatar asked Dec 06 '11 14:12

markzzz


People also ask

How do I read an XML string?

In this article, you will learn three ways to read XML files as String in Java, first by using FileReader and BufferedReader, second by using DOM parser, and third by using open-source XML library jcabi-xml.

Which function is used to read XML data from a string?

The PHP simplexml_load_string() function is used to read XML data from a string.

What is the best way to read XML in C#?

The XmlReader class in C# provides an efficient way to access XML data. XmlReader. Read() method reads the first node of the XML file and then reads the whole file using a while loop.

How do I read an XML string in Python?

Example Read XML File in Python To read an XML file, firstly, we import the ElementTree class found inside the XML library. Then, we will pass the filename of the XML file to the ElementTree. parse() method, to start parsing. Then, we will get the parent tag of the XML file using getroot() .


1 Answers

You should use LoadXml method, not Load:

xmlDoc.LoadXml(myXML);  

Load method is trying to load xml from a file and LoadXml from a string. You could also use XPath:

XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(xml);  string xpath = "myDataz/listS/sog"; var nodes = xmlDoc.SelectNodes(xpath);  foreach (XmlNode childrenNode in nodes) {     HttpContext.Current.Response.Write(childrenNode.SelectSingleNode("//field1").Value); }  
like image 72
Andrey Marchuk Avatar answered Sep 17 '22 12:09

Andrey Marchuk