Java DOM - 插入一个元素,在另一个元素之后
给定以下 XML 文件:
<?xml version="1.0" encoding="UTF-8"?>
<process
name="TestSVG2"
xmlns="http://www.example.org"
targetNamespace="http://www.example.org"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<sequence>
<receive name="Receive1" createInstance="yes"/>
<assign name="Assign1"/>
<invoke name="Invoke1"/>
<assign name="Assign2"/>
<reply name="Reply1"/>
</sequence>
</process>
我想在某个预先存在的元素之后添加一个新元素。例如,如果我想在 之后添加节点,则新的 XML 应该如下所示:<sequence></sequence>
"Assign1"
<sequence>
<receive name="Receive1" createInstance="yes"/>
<assign name="Assign1"/>
<newtype name="NewNode"/>
<invoke name="Invoke1"/>
<assign name="Assign2"/>
<reply name="Reply1"/>
</sequence>
我必须通过在函数中使用Java DOM来做到这一点。函数签名应如下所示:
public void addActionDom(String name, String stepType, String stepName)
哪里:
-
name
是预先存在的元素,之后将进行插入; -
stepType
是插入的元素类型; -
stepName
是新插入元素的 name 属性。
目前我缺乏JDOM或任何其他Java XML库的经验。你能不能给出一个示例代码,或者给我指出一个教程,在某个元素之后进行插入。
这是我到目前为止的代码:
public void addActionDom(String name, String stepType, String stepName) {
File xmlFile = new File(path + "/resources/" + BPELFilename);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db;
try {
/* Load XML */
db = dbf.newDocumentBuilder();
Document doc = db.parse(xmlFile);
doc.getDocumentElement().normalize();
/* Iterate throughout the type tags and delete */
for (String cTag : typeTags) {
NodeList cnl = doc.getElementsByTagName(cTag);
for (int i = 0; i < cnl.getLength(); ++i) {
Node cnode = cnl.item(i);
if (cnode.getNodeType() == Node.ELEMENT_NODE) {
Element elem = (Element)cnode; // 'elem' Element after which the insertion should be made
if (elem.getAttribute("name").equals(name)) {
Element newElement = doc.createElement(stepType); // Element to be inserted
newElement.setAttribute("name", stepName);
// CODE HERE
}
}
}
}
/* Save the editing */
Transformer transformer =
TransformerFactory.newInstance().newTransformer();
StreamResult result =
new StreamResult(new FileOutputStream(path + "/resources/" +
BPELFilename));
DOMSource source = new DOMSource(doc);
transformer.transform(source, result);
} catch (Exception e) {
/* ParserConfigurationException */
/* SAXException */
/* IOException */
/* TransformerConfigurationException */
/* TransformerException */
/* Exception */
e.printStackTrace();
}
}
}