下面的程序将向您展示如何向XML元素添加属性。使用JDOM库,可以通过调用Element的setAttribute(String name, String value)方法轻松完成此操作。
package org.nhooo.example.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(); } } }
输出结果如下:
<?xml version="1.0" encoding="UTF-8"?> <root> <row userid="alice"> <name firstname="Alice" lastname="Starbuzz" /> </row> </root>
Maven依赖
<!-- https://search.maven.org/remotecontent?filepath=org/jdom/jdom2/2.0.6/jdom2-2.0.6.jar --> <dependency> <groupId>org.jdom</groupId> <artifactId>jdom2</artifactId> <version>2.0.6</version> </dependency>