java操作dom节点的添加_Java DOM-依次插入一个元素

给定以下XML文件:

name="TestSVG2"

xmlns="http://www.example.org"

targetNamespace="http://www.example.org"

xmlns:xsd="http://www.w3.org/2001/XMLSchema">

我想 在某个预先存在的元素之后 添加一个新 元素

。例如,如果要在之后添加节点"Assign1",则新的XML应该如下所示:

我必须通过在函数中使用Java DOM来执行此操作。函数签名应如下所示:

public void addActionDom(String name, String stepType, String stepName)

哪里:

name 是预先存在的元素,之后将进行插入;

stepType 是插入的元素类型;

stepName 是新插入的元素的名称属性。

目前,我缺乏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();

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值