3

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?

1 Answer 1

4

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 (e.g: 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.

Sign up to request clarification or add additional context in comments.

5 Comments

Thank you this worked! But now if I want to access an element inside SECTION how do i do it? it returns null if i use Element(name).
@FenrisL that's already been answered multiple times, googling should give you some answers as well, see here stackoverflow.com/questions/8460464/… - another option to use XPath stackoverflow.com/questions/6209841/…
Right (+1) but I removed the part about xsi:SECTION, which is misguided as the xsi prefix for http://www.w3.org/2001/XMLSchema-instance would never be used as a prefix to SECTION in that manner. See xmlns, xmlns:xsi, xsi:schemaLocation, and targetNamespace? for further details.
@kjhughes do you mean that xsi should not be used as prefix for arbitrary xml elements? I think the matter of this question is not related to any standards (e.g: the XSD specification), it's more related to how an element is prefixed, as in case of the OP's question, he does not even know that the SECTION element is actually not prefixed at all. I think instead of removing that part, you should have added additional note about the special xsi prefix.
Yes, it is possible to use xsi in such a manner, but it would be unconventional and misleading. Your answer already nailed OP's issue. Using xsi like that on SECTION, or explaining why one should not when OP did not, would be totally tangential to OP's problem, which, again, you already explained well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.