为什么的XDocument不能得到元素这项wellform XML文本呢? [英] Why XDocument can't get element out of this wellform XML text?
问题描述
我想从以下XML文本地址
元素的值,但它没有找到它,除非我删除的xmlns = http://www.foo.com
从根
元素。然而,XML是即使它有效。有什么问题吗?
由于我收到从Web服务的XML文本,我不拥有控制权,但我可以带出的的xmlns
的一部分,如果我必须作为最后的手段。
<?XML ?版本=1.0编码=UTF-8>
<根的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>
<地址>主街SW< /地址>
< /根>
VAR DOC =的XDocument .Parse(xmlTextAbove);
VAR地址= doc.Descendants()式(O => o.Name ==地址)。FirstOrDefault()。
Console.WriteLine(address.Value); //< - 错误,地址为null。
当你的XML包含一个命名空间,就不得不提在代码。这将工作:
的XNamespace nsSys =http://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 =http://www.w3.org/2001/XMLSchema-instance
的xmlns:XSD =http://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屋!