从xml获得xml节点值字符串
问题描述:
我有一个包含xml命名空间的xml。我需要从它的XML节点获得价值从xml获得xml节点值字符串
<personxml:person xmlns:personxml="http://www.your.example.com/xml/person" xmlns:cityxml="http://www.my.example.com/xml/cities">
<personxml:name>Rob</personxml:name>
<personxml:age>37</personxml:age>
<cityxml:homecity>
<cityxml:name>London</cityxml:name>
<cityxml:lat>123.000</cityxml:lat>
<cityxml:long>0.00</cityxml:long>
</cityxml:homecity>
现在我想获取标记<cityxml:lat>
的价值123.00
代码:
string xml = "<personxml:person xmlns:personxml='http://www.your.example.com/xml/person' xmlns:cityxml='http://www.my.example.com/xml/cities'><personxml:name>Rob</personxml:name><personxml:age>37</personxml:age><cityxml:homecity><cityxml:name>London</cityxml:name><cityxml:lat>123.000</cityxml:lat><cityxml:long>0.00</cityxml:long></cityxml:homecity></personxml:person>";
var elem = XElement.Parse(xml);
var value = elem.Element("OTA_personxml/cityxml:homecity").Value;
错误我得到
The '/' character, hexadecimal value 0x2F, cannot be included in a name.
答
您需要使用XNamespace。例如:
XNamespace ns1 = "http://www.your.example.com/xml/person";
XNamespace ns2 = "http://www.my.example.com/xml/cities";
var elem = XElement.Parse(xml);
var value = elem.Element(ns2 + "homecity").Element(ns2 + "name").Value;
//value = "London"
使用包含URI的字符串创建XNamespace,然后将名称空间与本地名称组合在一起。
欲了解更多信息,请参阅here。
答
您最好使用XmlDocument来导航您的xml。
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
XmlNode node = doc.SelectSingleNode("//cityxml:homecity/cityxml:lat");
string latvalue = null;
if (node != null) latvalue = node.InnerText;
答
我用你的代码得到的是,需要有解析XML命名空间适当 尝试错误:
XNamespace ns1 = "http://www.your.example.com/xml/cities";
string value = elem.Element(ns1 + "homecity").Element(ns1 + "name").Value;
我仍然会用XDocuments建议,如果可能的话分析,但上述是罚款如果你的方式是必须的。
如何尝试像这样 'elem.SelectSingleNode(“/ cityxml:homecity/@ value”)。Value' – MethodMan 2014-09-10 14:52:40