XML Elements
XML elements are the building blocks of an XML document. They contain data and can have attributes, text, or nested elements.
1. Basic XML Element Structure
<book>
<title>XML Basics</title>
<author>John Doe</author>
<year>2024</year>
</book>
<book>
is the parent element.<title>
,<author>
, and<year>
are child elements.
2. Nested XML Elements
<library>
<book>
<title>XML Basics</title>
<author>John Doe</author>
</book>
<book>
<title>Advanced XML</title>
<author>Jane Smith</author>
</book>
</library>
<library>
is the root element.<book>
elements are children of<library>
.<title>
and<author>
are children of<book>
.
3. Empty XML Elements
Elements can be empty and written in self-closing format:
<book title="XML Basics" />
4. Accessing XML Elements in JavaScript
You can read XML elements using JavaScript.
Example XML File (data.xml)
<books>
<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>
</books>
JavaScript to Parse XML Elements
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;
let year = books[i].getElementsByTagName("year")[0].textContent;
output += `<li>${title} by ${author} (${year})</li>`;
}
output += "</ul>";
document.getElementById("output").innerHTML = output;
}
};
xhr.send();
getElementsByTagName("title")[0].textContent
extracts the text from an element.
5. Validating Elements with XSD
Example XSD Schema (schema.xsd)
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="books">
<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>
- Defines required structure for XML elements.
- Ensures
<title>
,<author>
, and<year>
are present inside<book>
.
Key Takeaways
- Elements store main data, while attributes store metadata.
- Nested elements allow hierarchical data structures.
- JavaScript can read elements using
getElementsByTagName()
. - XSD can enforce element structure and data types.
Would you like an example of modifying XML elements dynamically?
0 comments:
Post a Comment