XML Coding Notes

Learn XML Coding

1. Introduction to XML

XML (eXtensible Markup Language) is a markup language used to store and transport data in a structured format. It is both human-readable and machine-readable.

2. XML Syntax

<?xml version="1.0" encoding="UTF-8"?>
<note>
    <to>John</to>
    <from>Alice</from>
    <message>Hello, how are you?</message>
</note>
    

3. XML Elements & Tags

Elements are the building blocks of XML, enclosed in start and end tags.

<book>
    <title>XML Guide</title>
    <author>John Doe</author>
    <year>2025</year>
</book>
    

4. XML Attributes

Attributes provide additional information about an element.

<book title="XML Guide" author="John Doe" year="2025"></book>
    

5. XML Namespaces

Namespaces prevent element name conflicts.

<root xmlns:lib="http://www.library.com">
    <lib:book>
        <lib:title>XML Guide</lib:title>
    </lib:book>
</root>
    

6. XML Schemas (XSD)

XML Schema (XSD) defines the structure and rules for an XML document.

<xs:element name="book">
    <xs:complexType>
        <xs:sequence>
            <xs:element name="title" type="xs:string"/>
            <xs:element name="author" type="xs:string"/>
        </xs:sequence>
    </xs:complexType>
</xs:element>
    

7. XML Parsing

Parsing converts XML into readable or usable formats for applications.

Java Example:

import javax.xml.parsers.*;
import org.w3c.dom.*;

public class XMLParser {
    public static void main(String[] args) throws Exception {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse("file.xml");

        NodeList list = doc.getElementsByTagName("title");
        System.out.println(list.item(0).getTextContent());
    }
}
    

8. XSLT (Extensible Stylesheet Language Transformations)

XSLT is used to transform XML data into other formats (like HTML).

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="/">
        <html>
            <body>
                <h2>Book List</h2>
                <xsl:for-each select="library/book">
                    <p><xsl:value-of select="title"/> by <xsl:value-of select="author"/></p>
                </xsl:for-each>
            </body>
        </html>
    </xsl:template>
</xsl:stylesheet>
    

9. Applications of XML

  • Configuration files (e.g., AndroidManifest.xml in Android)
  • Data storage and exchange (e.g., RSS feeds, Web Services)
  • APIs (e.g., SOAP APIs)
  • UI Layouts (e.g., Android UI)

10. Conclusion

XML is a powerful language for data storage and transmission. It plays a key role in APIs, configurations, and structured document formatting.