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)

原文地址:https://www.cnblogs.com/hfutwyy/p/2367123.html