XML Tree Structure
XML documents are structured in a hierarchical tree format, where elements are arranged as parent-child relationships.
1. Understanding XML Tree Structure
Consider this XML document:
<library>
<book>
<title>XML Basics</title>
<author>John Doe</author>
<year>2024</year>
</book>
<book>
<title>Advanced XML</title>
<author>Jane Smith</author>
<year>2023</year>
</book>
</library>
Tree Representation:
library (Root)
│
├── book (Parent)
│ ├── title: XML Basics (Child)
│ ├── author: John Doe (Child)
│ └── year: 2024 (Child)
│
└── book (Parent)
├── title: Advanced XML (Child)
├── author: Jane Smith (Child)
└── year: 2023 (Child)
<library>
is the root element.- Each
<book>
is a child of<library>
. <title>
,<author>
, and<year>
are children of<book>
.<library>
is the ancestor of all elements inside it.
2. XML Tree Terminology
3. Accessing XML Tree with JavaScript
We can navigate the XML tree using JavaScript.
Example JavaScript to Access XML Tree
let xhr = new XMLHttpRequest();
xhr.open("GET", "data.xml", true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
let xmlDoc = xhr.responseXML;
let books = xmlDoc.getElementsByTagName("book");
let output = "<ul>";
for (let i = 0; i < books.length; i++) {
let title = books[i].getElementsByTagName("title")[0].textContent;
let author = books[i].getElementsByTagName("author")[0].textContent;
output += `<li>${title} by ${author}</li>`;
}
output += "</ul>";
document.getElementById("output").innerHTML = output;
}
};
xhr.send();
getElementsByTagName("book")
retrieves all<book>
elements.getElementsByTagName("title")[0].textContent
fetches the title from each book.
4. Navigating XML Tree Using XPath
XPath allows querying XML documents using expressions.
Example: XPath Queries
5. Validating XML Tree Structure with XSD
Example XML Schema (XSD)
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="library">
<xs:complexType>
<xs:sequence>
<xs:element name="book" maxOccurs="unbounded">
<xs:complexType>
<xs:sequence>
<xs:element name="title" type="xs:string"/>
<xs:element name="author" type="xs:string"/>
<xs:element name="year" type="xs:int"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
- This schema ensures that every
<library>
contains multiple<book>
elements. - Each
<book>
must have a<title>
,<author>
, and<year>
.
Key Takeaways
- XML is structured as a tree, with a root and nested elements.
- Elements can have parents, children, and siblings.
- JavaScript and XPath allow navigation of the XML tree.
- XML Schema (XSD) helps validate the structure.
Would you like an interactive XML tree visualization example?
0 comments:
Post a Comment