The program below will show you how to add attributes to an XML elements. Using JDOM library this can be easily done by calling the Element
‘s setAttribute(String name, String value)
method.
package org.kodejava.jdom;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
public class JDOMAddAttribute {
public static void main(String[] args) {
Document doc = new Document();
Element root = new Element("root");
// Create <row userid="alice"></row>
Element child = new Element("row").setAttribute("userid", "alice");
// Create <name firstname="Alice" lastname="Starbuzz"></name>
Element name = new Element("name")
.setAttribute("firstname", "Alice")
.setAttribute("lastname", "Starbuzz");
child.addContent(name);
root.addContent(child);
doc.addContent(root);
XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
try {
outputter.output(doc, System.out);
} catch (Exception e) {
e.printStackTrace();
}
}
}
And here goes the output:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<row userid="alice">
<name firstname="Alice" lastname="Starbuzz" />
</row>
</root>
Maven Dependencies
<dependency>
<groupId>org.jdom</groupId>
<artifactId>jdom2</artifactId>
<version>2.0.6.1</version>
</dependency>
Latest posts by Wayan (see all)
- How do I create a string of repeated characters? - September 1, 2023
- How do I convert datetime string with optional part to a date object? - August 28, 2023
- How do I split large excel file into multiple smaller files? - April 15, 2023