XML Attributes

XML Attributes

XML attributes provide additional information about elements. They are always placed inside the opening tag of an element.


1. Basic XML Attribute Example

<book title="XML Basics" author="John Doe" year="2024"/>

Here:

  • title, author, and year are attributes of the <book> element.

2. XML Attributes vs Elements

You can store data using either attributes or elements:

Using Attributes:

<book title="XML Basics" author="John Doe" year="2024"/>

Using Elements:

<book>
    <title>XML Basics</title>
    <author>John Doe</author>
    <year>2024</year>
</book>

When to Use What?


3. Accessing XML Attributes in JavaScript

Example XML File (data.xml)

<books>
    <book title="XML Basics" author="John Doe" year="2024"/>
    <book title="Advanced XML" author="Jane Smith" year="2023"/>
</books>

JavaScript to Read Attributes

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].getAttribute("title");
            let author = books[i].getAttribute("author");
            let year = books[i].getAttribute("year");
            output += `<li>${title} by ${author} (${year})</li>`;
        }
        output += "</ul>";
        document.getElementById("output").innerHTML = output;
    }
};
xhr.send();

This extracts and displays attribute values from the XML.


4. Validating Attributes with XSD

If using XML Schema (XSD), you can enforce attribute rules:

Example XSD (schema.xsd)

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element name="book">
        <xs:complexType>
            <xs:attribute name="title" type="xs:string" use="required"/>
            <xs:attribute name="author" type="xs:string" use="required"/>
            <xs:attribute name="year" type="xs:int" use="optional"/>
        </xs:complexType>
    </xs:element>
</xs:schema>
  • use="required" makes the attribute mandatory.
  • use="optional" allows it to be omitted.

Key Takeaways

  • Attributes store metadata about an element.
  • Use elements for main data, attributes for additional details.
  • JavaScript can access attributes using getAttribute().
  • XSD can enforce attribute rules.

Would you like an example of modifying XML attributes dynamically?

Share on Google Plus

About It E Research

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment