Java DOM - 插入一个元素,又一个 [英] Java DOM - Inserting an element, after another

查看:103
本文介绍了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>

我想在< sequence>< / sequence> 之后的某个预先存在的元素。例如,如果我想在Assign1之后添加节点,则新的XML应如下所示:

I want to add a new element inside the <sequence></sequence> after a certain pre-existing element. For example if I want to add the node after "Assign1", the new XML should like this:

   <sequence>
      <receive name="Receive1" createInstance="yes"/>
      <assign name="Assign1"/>
      <newtype name="NewNode"/>
      <invoke name="Invoke1"/>
      <assign name="Assign2"/>
      <reply name="Reply1"/>
   </sequence>

我必须在一个函数中使用Java DOM来做到这一点。函数签名应该如下所示:

I have to do this by using Java DOM, in a function. The function signature should like this:

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

其中:


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

  • stepType 是插入的元素类型;

  • stepName 是新插入元素的name属性。

  • name is the pre-existing element, after which the insertion will be made;
  • stepType is the inserted element type;
  • stepName is the name attribute of the newly inserted element.

目前,我没有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();
        }
    }
}


推荐答案

好吧,Aaron Digulla在速度上打败了我。不得不自己弄清楚自己。
我没有使用 cnl.item(i + 1) nextSibling()

Ok, Aaron Digulla beat me regarding speed. Had to figure it out myself as well. I didnt use cnl.item(i+1) but nextSibling():

Element newElement = doc.createElement(stepType); // Element to be inserted 
newElement.setAttribute("name", stepName);
elem.getParentNode().insertBefore(newElement, elem.getNextSibling());

您不能在指定索引处插入节点。唯一的节点插入方法是

You cannot insert Nodes at a specified index. The only node-inserting methods are

appendChild(Node node) //appends the given child to the end of the list of children

insertBefore(Node new, Node child) //inserts "new" into the list, before the 'child' node.

如果有一个insertAfter(Node new,Node child)方法,这将很容易。但是不幸的是,不幸的是。

If there was a insertAfter(Node new, Node child) method, this would be very easy for you. But there isn't, unfortunately.

这篇关于Java DOM - 插入一个元素,又一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆