Sample code for 30+ languages & platforms
Java

AddAttribute - Insert New Attribute in an XML Node

Demonstrates adding an name=value attribute to an XML element.

This example uses the XML sample file here: sample1.xml. The sample1.xml file contains this content:

Chilkat Java Downloads

Chilkat2 Java
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.Xml;

public class ChilkatExample {

    public static void main(String[] args) {
        Xml xml = new Xml();

        try {
            xml.loadXmlFile("qa_data/xml/sample1.xml");
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        // Navigate to the "books" element:
        try {
            xml.findChild2("books");
        } catch (ChilkatException e) {
            System.out.println("No books child found!");
            return;
        }

        int numChildren = xml.getNumChildren();

        int i = 0;
        while (i < numChildren) {
            // Navigate to the Nth book
            xml.getChild2(i);

            // Display the book title:
            System.out.println(xml.getAttrValue("title"));

            // Add a new integer attribute:
            // Should never fail..
            xml.addAttributeInt("bookId", i);

            // Add a new unread="yes" attribute:
            xml.addAttribute("unread", "yes");

            // Navigate back up to the parent:
            xml.getParent2();

            i = i + 1;
        }

        // Navigate back to the document root:
        xml.getRoot2();

        // Save the updated document:
        try {
            xml.saveXml("modified.xml");
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        System.out.println(xml.getXml());
    }
}