本示例说明如何设置XML元素的文本内容。在JDOM中,我们可以轻松插入诸如HTML标签之类的文本,而不必担心转义标签。JDOM将自动执行此转换。
package org.nhooo.example.jdom; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.JDOMException; import org.jdom2.input.SAXBuilder; import org.jdom2.output.Format; import org.jdom2.output.XMLOutputter; import java.io.IOException; import java.io.StringReader; public class JDOMSetTextContent { public static void main(String[] args) { String xml = "<root>" + " <description>" + " </description>" + "</root>"; SAXBuilder builder = new SAXBuilder(); try { Document document = builder.build(new StringReader(xml)); Element root = document.getRootElement(); Element description = root.getChild("description"); //将文本内容添加到description元素。字符串 // 会自动转义,因此我们不必使用 // < and > symbol. description.setText("This is an <strong>IMPORTANT</strong> " + "description"); XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat()); outputter.output(document, System.out); } catch (JDOMException | IOException e) { e.printStackTrace(); } } }
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>