dom4j将元素转换为字符串
时间: 2023-08-04 22:08:13 浏览: 142
dom4j解析字符串
使用dom4j将元素转换为字符串可以使用XMLWriter类,示例如下:
```java
import java.io.StringWriter;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
public class Dom4jElementToString {
public static void main(String[] args) {
Document document = DocumentHelper.createDocument();
Element root = document.addElement("root");
Element child = root.addElement("child");
child.addAttribute("attribute", "value");
child.addText("text");
StringWriter writer = new StringWriter();
OutputFormat format = OutputFormat.createPrettyPrint();
XMLWriter xmlWriter = new XMLWriter(writer, format);
try {
xmlWriter.write(document.getRootElement());
xmlWriter.flush();
System.out.println(writer.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
输出结果:
```
<root>
<child attribute="value">text</child>
</root>
```
阅读全文