由网友(清羽ζ淡墨)分享简介:我有这样的XML(存储在一个名为C#字符串与myXML )I have this XML (stored in a C# string called myXML)我有这样的XML(存储在一个名为C#字符串
与myXML
)
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>
和我想浏览所有&LT; SOG&GT;
元素。对于每个人,我想打印子&LT;字段1&GT;
and I'd like to browse all <sog>
elements. For each of them, I'd like to print the child <field1>
.
所以这是我的code:
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);
}
但似乎我不能读一个字符串作为XML?我得到 System.ArgumentException
推荐答案
您应该使用loadXML的方法,而不是负载:
You should use LoadXml method, not Load:
xmlDoc.LoadXml(myXML);
Load方法试图从一个字符串的文件和loadXML的加载XML。你也可以使用XPath:
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);
}
相关推荐
最新文章