Read a XML (from a string) and get some fields – Problems reading XML
Read a XML (from a string) and get some fields – Problems reading XML
Use the LoadXml method, and not Load to read xml from string
xmlDoc.LoadXml(myXML);
The method Load will try to load xml from a file and LoadXml from a string. Also we can 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); }
Alternately use the Linq-XML,
XDocument doc = XDocument.Load(file); var result = from ele in doc.Descendants("sog") select new { field1 = (string)ele.Element("field1") }; foreach (var t in result) { HttpContext.Current.Response.Write(t.field1); }
Else, get the node list of <sog> tag.
XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(myXML); XmlNodeList parentNode = xmlDoc.GetElementsByTagName("sog"); foreach (XmlNode childrenNode in parentNode) { HttpContext.Current.Response.Write(childrenNode.SelectSingleNode("field1").InnerText); }
Try this code:
XDocument xdoc = new XDocument(); xdoc = XDocument.Parse(xml_string);
string textXml = "<xmlroot><firstchild>value of first child</firstchild>........</xmlroot>";
XElement xmlroot = XElement.Parse(textXml);
string firstNodeContent = ((System.Xml.Linq.XElement)(xmlroot.FirstNode)).Value;
2
I used the System.Xml.Linq.XElement for the purpose. Just check code below for reading the value of first child node of the xml(not the root node).
string textXml = "<xmlroot><firstchild>value of first child</firstchild>........</xmlroot>";
XElement xmlroot = XElement.Parse(textXml);
string firstNodeContent = ((System.Xml.Linq.XElement)(xmlroot.FirstNode)).Value;
?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>
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);
}
XDocument doc = XDocument.Load(file);
var result = from ele in doc.Descendants("sog")
select new
{
field1 = (string)ele.Element("field1")
};
foreach (var t in result)
{
HttpContext.Current.Response.Write(t.field1);
}
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(myXML);
XmlNodeList parentNode = xmlDoc.GetElementsByTagName("sog");
foreach (XmlNode childrenNode in parentNode)
{
HttpContext.Current.Response.Write(childrenNode.SelectSingleNode("field1").InnerText);
}