Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
142 views
in Technique[技术] by (71.8m points)

c# - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
} 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...