简体   繁体   English

从xml字符串中获取xml节点值

[英]get xml node value from xml string

I have xml which contain xml namespace. 我有xml包含xml命名空间。 i need to get value from its xml node 我需要从其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>

Now i want to get value of tag <cityxml:lat> as 123.00 现在我想获得标签<cityxml:lat>值为123.00

Code : 代码:

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;

Error i am getting 我得到的错误

The '/' character, hexadecimal value 0x2F, cannot be included in a name.

You are better off using a XmlDocument to navigate your xml. 最好使用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;

You need to use XNamespace. 您需要使用XNamespace。 For example: 例如:

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"

Create XNamespace using a string that contains the URI, then combine the namespace with the local name. 使用包含URI的字符串创建XNamespace,然后将命名空间与本地名称组合。

For more information, see here . 有关更多信息,请参阅此处

The error I got with your code was that there needs to be a namespace to parse the XML properly Try : 我在代码中遇到的错误是需要有一个名称空间来正确解析XML尝试:

 XNamespace ns1 = "http://www.your.example.com/xml/cities";
 string value = elem.Element(ns1 + "homecity").Element(ns1 + "name").Value;

I would still advice using XDocuments to parse if possible, but the above is fine if your way is a must. 如果可能的话,我仍然会建议使用XDocuments进行解析,但如果你的方式是必须的话,上面的方法很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM