为什么的XDocument不能得到元素这项wellform XML文本呢? [英] Why XDocument can't get element out of this wellform XML text?

查看:143
本文介绍了为什么的XDocument不能得到元素这项wellform XML文本呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从以下XML文本地址元素的值,但它没有找到它,除非我删除的xmlns = http://www.foo.com元素。然而,XML是即使它有效。有什么问题吗?



由于我收到从Web服务的XML文本,我不拥有控制权,但我可以带出的的xmlns 的一部分,如果我必须作为最后的手段。

 <?XML ?版本=1.0编码=UTF-8> 
<根的xmlns:XSI =htt​​p://www.w3.org/2001/XMLSchema-instance
的xmlns:XSD =htt​​p://www.w3.org/2001/XMLSchema
的xmlns:XSI =http://www.w3.org/2001/XMLSchema-instance
的xmlns:XSD =http://www.w3.org/2001/XMLSchema
的xmlns =htt​​p://www.foo.com>
<地址>主街SW< /地址>
< /根>





  VAR DOC =的XDocument .Parse(xmlTextAbove); 
VAR地址= doc.Descendants()式(O => o.Name ==地址)。FirstOrDefault()。
Console.WriteLine(address.Value); //< - 错误,地址为null。


解决方案

当你的XML包含一个命名空间,就不得不提在代码。这将工作:

 的XNamespace nsSys =htt​​p://www.foo.com; 
XDOC的XElement = XElement.Load(1.XML);
的XElement xEl2 = xDoc.Descendants(nsSys +地址)FirstOrDefault()。



不过,我不得不改变你的XML一点点,因为它包含重复 XMLNS:XSI 的xmlns:XSD 应每XML格式只出现一次:

 <?XML版本=1.0编码=UTF-8>?; 
<根的xmlns:XSI =htt​​p://www.w3.org/2001/XMLSchema-instance
的xmlns:XSD =htt​​p://www.w3.org/2001/XMLSchema
的xmlns =http://www.foo.com>
<地址>主街SW< /地址>
< /根>



相关文章在MSDN:的的XNamespace类


I'm trying to get the value of the Address element from the following XML text, but it's not finding it unless I remove xmlns="http://www.foo.com" from the Root element. However, the XML is valid even with it. What's the problem here?

Since I'm getting the XML text from a web service, I don't have control over it, but I can strip out the xmlns part if I have to as the last resort.

<?xml version="1.0" encoding="utf-8"?>
<Root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
      xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
      xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
      xmlns="http://www.foo.com">
  <Address>Main St SW</Address>
</Root>

var doc = XDocument.Parse(xmlTextAbove);
var address = doc.Descendants().Where(o => o.Name == "Address").FirstOrDefault();
Console.WriteLine(address.Value); // <-- error, address is null.

解决方案

As your xml contains a namespace, you have to mention that in code. This will work:

    XNamespace nsSys = "http://www.foo.com";
    XElement xDoc = XElement.Load("1.xml");
    XElement xEl2 = xDoc.Descendants(nsSys + "Address").FirstOrDefault();

However I had to change your xml a little bit, as it contained repeated xmlns:xsi and xmlns:xsd which should occur only once per xml format:

<?xml version="1.0" encoding="utf-8"?>
<Root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:xsd="http://www.w3.org/2001/XMLSchema"
      xmlns="http://www.foo.com" >
  <Address>Main St SW</Address>
</Root>

Related article in MSDN: XNamespace Class

这篇关于为什么的XDocument不能得到元素这项wellform XML文本呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆