Examples
Let's take a look at an example xml file.
<ns1:root xmlns:ns1="http://example.com/ns1">
<child></child>
</ns1:root>
</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>
</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>
</ns0:root>
In this example, <root>'s namespace is "http://example.com/ns0", while <child>'s namespace is "http://example.com/ns1".
Conclusion
- non-prefixed namespace affects the containing element and its children.
- prefixed namespace has higher priority, but only affects the prefixed element, not its children.
Steps to figure out the namespace of an XML element
- If its tag is prefixed, then that prefixed namespace is its namespace. Otherwise
- If it has `xmlns="https://example.com/nsx"`, then its namespace is "https://example.com/nsx". Otherwise
- If its parent has `xmlns="https://example.com/nsx"`, then its namespace is "https://example.com/nsx". Otherwise,
- Repeat 3
- 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>
</ns1:root>
Q2.xml
<root
xmlns:ns1="http://example.com/ns1"
xmlns="http://example.com/ns0">
<middle>
<ns1:child></ns1:child>
<middle>
</root>
</root>
No comments:
Post a Comment