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
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.
The PHP simplexml_load_string() function is used to read XML data from a string.
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.
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() .
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With