一、添加依赖(版本自行更改)
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>2.1.3</version>
</dependency>
二、使用Document对象的方法来操作XML文档。例如,获取根元素、获取指定元素、修改元素属性等:
方法一:
SAXReader reader = new SAXReader();
Document doc = reader.read("example.xml");
方法二:
private byte[] medContent;
InputStream inputStream = new ByteArrayInputStream(new String(MedVO.getContent(), StandardCharsets.UTF_8).getBytes(StandardCharsets.UTF_8));
Document doc = new SAXReader().read(inputStream);
inputStream.close();
方法三:
import org.dom4j.DocumentHelper;
Document doc = DocumentHelper.parseText(XmlStrings.HOSPITALIZATION_DIAGNOSIS);
public static void main(String[] args) {
Map map = ....;
Iterator it = doc.getRootElement().elementIterator();
while (it.hasNext()) {
org.dom4j.Element nextRoot = (org.dom4j.Element) it.next();
Iterator nextIt = nextRoot.elementIterator();
if (nextIt.hasNext()) {
getTemplateMap(nextIt, map);
} else {
if ("InnerValue".equals(nextRoot.getName())) {
if (null != map.get(nextRoot.getText())) {
nextRoot.getParent().element("XElements").element("Element").element("Text").setText(map.get(nextRoot.getText()).toString());
}
}
if ("AttributeNameForContactAction".equals(nextRoot.getName())) {
if (null != map.get(nextRoot.getText())) {
nextRoot.setText(map.get("daqtaskid").toString());
}
}
}
}
}