Why XDocument can't get element out of this wellform XML text?

蓝咒 提交于 2019-12-31 02:49:06

问题


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.

回答1:


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




回答2:


The document root's XML namespace is included in the textual representation of o.Name, which is actually an instance of XName so the condition never matches.

The easiest fix is to use LocalName for the comparison:

.Where(o => o.Name.LocalName == "Address")


来源:https://stackoverflow.com/questions/14390749/why-xdocument-cant-get-element-out-of-this-wellform-xml-text

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!