简体   繁体   English

将节点添加到节点XML dom4j

[英]add node to a node XML dom4j

In DOM4J and XML how to add a node to an existing node? 在DOM4J和XML中,如何将节点添加到现有节点?

If I follow the example its very easy and works great if I have an element already. 如果我遵循该示例,那么它非常容易,并且如果已经有了元素,则效果很好。

Element root = doc.getRootElement();
Element someElement = root.addElement("some");
Element anotherElement = someElement.addElement("another");

and so forth. 等等。 Easy if I have an Element object. 如果我有一个Element对象,这很容易。

but once I lose a reference or am loading an xml and not creating one from scratch I just can't wrap my head around how I add a node /element exactly where I want. 但是一旦我丢失了一个引用或加载了一个xml而不是从头开始创建一个xml,我就无法将我的头完全围绕在我想要的位置添加节点/元素的方式。

So the specific question is: Given a document and an specific element in it, how do I add an element underneath it? 因此,特定的问题是:给定文档和文档中的特定元素,如何在文档下方添加元素? Do I have to iterate through the whole document? 我是否需要遍历整个文档? Xpath I can only get to return nodes which have no .addElement and I can't turn it into an element. Xpath我只能返回没有.addElement的节点,也不能将其转换为元素。 Im simply stumped and aside from adding an ID=? 我只是迷住了,除了添加ID =? to every single node I just cant figure out how to put something exactly where I want it to go. 对于每个节点,我只是想不出如何将某些东西放到我想要的地方。 Any help or direction would be greatly appreciated. 任何帮助或指示将不胜感激。

You can either iterate and check the required node and add the newly created node to it or you can use and xpath expression to get the particular node and add new node to it. 您可以迭代并检查所需的节点,然后将新创建的节点添加到其中,也可以使用xpath表达式来获取特定的节点,并将新节点添加到其中。

Iteration: 迭代:

    public void iterateNodes() {
     SAXReader reader = new SAXReader();
     Document document = reader.read("yourxml.xml");
     Element root = document.getRootElement();
     for ( Iterator i = root.elementIterator(); i.hasNext(); ){
           Element row = (Element) i.next();
           Iterator itr = row.elementIterator();
           while(itr.hasNext()) {
                Element child = (Element) itr.next();
                String name = child.getQualifiedName();
                if(name.equals("requiredName") {
                   //create node and add it to child.
                }   
           }
     }
 }

XPath: XPath:

public void addNodeUsingXpath() {
    SAXReader reader = new SAXReader();
     Document document = reader.read("yourxml.xml");
        String xpathExpression = "yourxpath";
        List<Node> nodes = document.selectNodes(xpathExpression);
        // nodes will have all the child nodes under your Xpath.
        for (Node node : nodes) {
           //get the required node and add your new node to specific node.
            if(node instanceof Element) {
                 Element e = (Element) node;
                 e.addElement("newElement");
                 ....
            }
        }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM