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?

FenrisL
  • 287
  • 5
  • 17

1 Answers1

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.

kjhughes
  • 106,133
  • 27
  • 181
  • 240
King King
  • 61,710
  • 16
  • 105
  • 130
  • 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 Apr 03 '21 at 10:23
  • 1
    @FenrisL that's already been answered multiple times, googling should give you some answers as well, see here https://stackoverflow.com/questions/8460464/finding-element-in-xdocument/45835388 - another option to use XPath https://stackoverflow.com/questions/6209841/how-to-use-xpath-with-xdocument – King King Apr 03 '21 at 10:26
  • 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?](https://stackoverflow.com/q/34202967/290085) for further details. – kjhughes Apr 03 '21 at 14:17
  • @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. – King King Apr 03 '21 at 14:25
  • 1
    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. – kjhughes Apr 03 '21 at 14:35