Pages

Sunday, 10 September 2023

XML child element do NOT inherit parent's namespace!

Examples

 Let's take a look at an example xml file.

<ns1:root xmlns:ns1="http://example.com/ns1">
  <child></child>
</ns1:root>

What's the namespace of element <Child>?

If your anser is "http://example.com/ns1", continue to read!


The correct answer is "",  which is also called the default xml namespace.

Child nodes do NOT inherit prefixed namespace.

Now, see another example xml file.

<root xmlns="http://example.com/ns1">
  <child></child>
</root>

For this example, <child>'s namespace is "http://example.com/ns1".

Child nodes inherit non-prefixed namespace.

Another example.

<ns0:root 
  xmlns:ns0="http://example.com/ns0" 
  xmlns="http://example.com/ns1">
  <child></child>
</ns0:root>

In this example, <root>'s namespace is "http://example.com/ns0", while <child>'s namespace is "http://example.com/ns1".

Conclusion

  1. non-prefixed namespace affects the containing element and its children.
  2. prefixed namespace has higher priority, but only affects the prefixed element, not its children.

Steps to figure out the namespace of an XML element

  1. If its tag is prefixed, then that prefixed namespace is its namespace. Otherwise
  2. If it has `xmlns="https://example.com/nsx"`, then its namespace is "https://example.com/nsx". Otherwise
  3. If its parent has  `xmlns="https://example.com/nsx"`, then its namespace is "https://example.com/nsx". Otherwise,
  4. Repeat 3
  5. Otherwise, its namespace is the default xml namespace.

More Examples

Now, try to figure out the namespace of below <child>.

Q1.xml

<ns1:root 
  xmlns:ns1="http://example.com/ns1"
  xmlns="http://example.com/ns1">
  <child></child>
</ns1:root>

Q2.xml

<root 
  xmlns:ns1="http://example.com/ns1"
  xmlns="http://example.com/ns0">
  <middle>
    <ns1:child></ns1:child>
  <middle>
</root>


No comments:

Post a Comment