zoukankan      html  css  js  c++  java
  • XDocument读取带有命名空间的xml文档

    Linq to XML是非常强大的,它给我们带来了便捷的操作xml文档的方法。

    但是今天在做WP应用开发时遇到一个问题,

    如下XML:

    <?xml version="1.0" encoding="utf-8"?>
    <string xmlns="http://www.zhiyousoft.com/">

    <PhoneItemCollecion>

    <PhoneItem>

    <province>安徽</province>

    <city>合肥</city>

    <phonecode>1515698</phonecode>

    </PhoneItem>

    </PhoneItemCollecion>

    </string>

    利用XDocument读取居然不成功,但是去掉NameSpace却可以成功读取(这里的NameSpace是指 xmlns="http://www.zhiyousoft.com/",这是XML文档的NameSpace)

    查询代码如下:

    var query = from Phone in xdoc.Descendants("string").Descendants("PhoneItemCollecion").Descendants("PhoneItem")
    select new
    {
    prov = Phone.Element("province").Value,
    city = Phone.Element("city").Value
    };

    折腾了半天,找到解决方案:

    如下:

    string xml = e.Result;
    xml = xml.Replace("&lt;", "<");
    xml = xml.Replace("&gt;", ">");
    xml = xml.Replace("&amp;", "&");

    XElement rss = XElement.Parse(xml);
    XNamespace dc = "http://www.zhiyousoft.com/";
    IEnumerable<XElement> x = rss.Descendants(dc + "PhoneItem");
    foreach (XElement item in x)
    {
    this.tb_Phone.Text = item.Element(dc+"province").Value;

    }

    在XML查询中命名空间是非常重要的,由此可以看到(弄了一个半天和一个晚上的结论)。

    补充:

    上面这种方法可以实现,下面的也可以实现噢。

    XDocument xdoc = XDocument.Parse(xml);
    var query = from Phone in xdoc.Descendants(dc + "string").Descendants(dc + "PhoneItemCollecion").Descendants(dc + "PhoneItem")
    select new
    {
    prov = Phone.Element(dc+"province").Value,
    city = Phone.Element(dc+"city").Value
    };
    string result = "";
    foreach (var item in query)
    {
    result += item.prov;
    result += item.city;
    }

    (挚友软件站长原创 http://www.zhiyousoft.com)

  • 相关阅读:
    [Noi2011]阿狸的打字机
    Bzoj3530: [Sdoi2014]数数
    Bzoj2037: [Sdoi2008]Sue的小球
    Bzoj4869: [Shoi2017]相逢是问候
    Bzoj1899: [Zjoi2004]Lunch 午餐
    Bzoj3884: 上帝与集合的正确用法
    UVA10692:Huge Mods
    Bzoj1009: [HNOI2008]GT考试
    Bzoj1212: [HNOI2004]L语言
    【国家集训队2012】tree(伍一鸣)
  • 原文地址:https://www.cnblogs.com/hfutwyy/p/2367123.html
Copyright © 2011-2022 走看看