xmlDoc vs. Root Element

The xmlDoc of an XML document is not the same as the "root element" of the XML document. The xmlDoc node is imaginary, and sits above the root element.

Consider the following XML document:

<?xml version="1.0" encoding="UTF-8">
<?xml-stylesheet type="text/xsl" href="example.xsl"?>
<!-- This comment exists outside of the root element -->
<top>
    <item>I'm an item!</item>
    <item>So am I!</item>
</top>

Here, the xmlDoc has three xmlNode children:

  • The processing instruction that defines the XSL stylesheet

  • A comment node

  • The root element, <top>

Note that the information from the XML declaration (<?xml...) is not stored in a child node, but within the xmlDoc itself. See xmlTreeGetVersion() (here) and xmlTreeGetEncoding() (here) for more information.

This shows that although it's true that XML documents can only have one root element, an xmlDoc may have multiple children, and the root element may not be the first child of the xmlDoc.

This is why you should use xmlTreeGetRootElement() to get the root element of a document instead of xmlTreeGetFirstChild().


Copyright © Thunderstone Software     Last updated: Apr 15 2024
Copyright © 2024 Thunderstone Software LLC. All rights reserved.