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

本文关键字:xml 节点 获取 字符串 | 更新日期: 2023-09-27 18:21:27

我有包含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.

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

您需要使用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,然后将命名空间与本地名称组合。

有关更多信息,请参阅此处。

您最好使用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进行解析,但如果必须使用您的方法,以上内容也可以。