【问题标题】:get xml node value from xml string从 xml 字符串获取 xml 节点值
【发布时间】:2014-09-10 14:46:29
【问题描述】:

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

现在我想将标签&lt;cityxml:lat&gt; 的值设为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.

【问题讨论】:

  • 试试这样的东西怎么样elem.SelectSingleNode("/cityxml:homecity/@value").Value

标签: c# xml


【解决方案1】:

您需要使用 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

【讨论】:

  • 如何只得到nameLondon
  • @Shaggy var value = elem.Element(ns2 + "homecity").Element(ns2 + "name").Value;
【解决方案2】:

您最好使用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;

【讨论】:

    【解决方案3】:

    我在您的代码中遇到的错误是需要有一个命名空间来正确解析 XML 试试看:

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

    如果可能的话,我仍然建议使用 XDocuments 进行解析,但如果你的方式是必须的,上述方法很好。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多