简体   繁体   中英

Linq2XML can't find element with namespace

I have this XML

<SENDERS VERSION="V3.0.4" xsi:noNamespaceSchemaLocation="SENDERS.xd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <SECTION>
  </SECTION>
</SENDERS>

I am trying to parse it and find the element SECTION with the xsi namespace using the following code

var xdoc = XDocument.Parse(myxml);
var ns = xdoc.Root.GetNamespaceOfPrefix("xsi");
var section = xdoc.Element(ns + "SECTION");

Usually I do it this way but this time section is always null. Am I doing something wrong?

I think you remember it wrong. Actually the <SECTION> element does not have any explicit namespace prefix so it can only have a default namespace (which is declared without prefix).

Because your XML does not declare any default namespace (eg: xmlns=... ). So your <SECTION> has no namespace, the working code should be like this:

var section = xdoc.Root.Element("SECTION");

Another problem is you need to use XDocument.Root.Element instead of XDocument.Element .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM