如何将节点附加到java中的现有XML文件

时间:2021-01-14 14:05:32
public static void addALLToXML(Collection<Server> svr) throws IOException,
      ParserConfigurationException, TransformerException
{
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
        .newInstance();
    DocumentBuilder documentBuilder = documentBuilderFactory
        .newDocumentBuilder();
    Document document = documentBuilder.newDocument();

    // Root Element
    Element rootElement = document.createElement("Servers");
    document.appendChild(rootElement);

    for (Server i : svr)
    {
        // server elements
        Element server = document.createElement("server");
        rootElement.appendChild(server);

        Element name = document.createElement("name");
        name.appendChild(document.createTextNode(i.getName()));
        server.appendChild(name);

        Element port = document.createElement("port");
        port.appendChild(document.createTextNode(Integer.toString(i.getPort())));
        server.appendChild(port);
    }

    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    DOMSource source = new DOMSource(document);

    StreamResult result = new StreamResult("/home/user/server.xml");
    transformer.transform(source, result);
}

This is the function I need help with:

这是我需要帮助的功能:

public static void addNodeToXML(String nameIn, String portIn)
      throws ParserConfigurationException, SAXException, IOException
{
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
            .newInstance();
    DocumentBuilder documentBuilder = documentBuilderFactory
            .newDocumentBuilder();

    /* parse existing file to DOM */
    Document document = documentBuilder
            .parse(new File("/home/user/server.xml"));

    // Root Element
    Element rootElement = document.createElement("Servers");
    document.appendChild(rootElement);

    // server elements
    Element server = document.createElement("server");
    rootElement.appendChild(server);

    Element name = document.createElement("name");
    name.appendChild(document.createTextNode(nameIn));
    server.appendChild(name);

    Element port = document.createElement("port");
    port.appendChild(document.createTextNode(portIn));
    server.appendChild(port);
}

Original:

原版的:

<Servers>
 <server>
  <name>something</name>
  <port>port</port>
 </server>
 </Servers>

Wanted:

通缉:

<Servers> 
  <server>
   <name>something</name>
   <port>port</port>
  </server>
  <server>
   <name>something</name>
   <port>port</port>
  </server>
<Servers>

5 个解决方案

#1


29  

The following complete example will read an existing server.xml file from the current directory, append a new Server and re-write the file to server.xml. It does not work without an existing .xml file, so you will need to modify the code to handle that case.

以下完整示例将从当前目录中读取现有server.xml文件,附加新服务器并将该文件重新写入server.xml。没有现有的.xml文件它不起作用,因此您需要修改代码来处理这种情况。

import java.util.*;
import javax.xml.transform.*;
import javax.xml.transform.stream.*;
import javax.xml.transform.dom.*;
import org.w3c.dom.*;
import javax.xml.parsers.*;

public class AddXmlNode {
    public static void main(String[] args) throws Exception {

        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = documentBuilder.parse("server.xml");
        Element root = document.getDocumentElement();

        Collection<Server> servers = new ArrayList<Server>();
        servers.add(new Server());

        for (Server server : servers) {
            // server elements
            Element newServer = document.createElement("server");

            Element name = document.createElement("name");
            name.appendChild(document.createTextNode(server.getName()));
            newServer.appendChild(name);

            Element port = document.createElement("port");
            port.appendChild(document.createTextNode(Integer.toString(server.getPort())));
            newServer.appendChild(port);

            root.appendChild(newServer);
        }

        DOMSource source = new DOMSource(document);

        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        StreamResult result = new StreamResult("server.xml");
        transformer.transform(source, result);
    }

    public static class Server {
        public String getName() { return "foo"; }
        public Integer getPort() { return 12345; }
    }
}

Example server.xml file:

示例server.xml文件:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Servers>
  <server>
    <name>something</name>
    <port>port</port>
  </server>
</Servers>

The main change to your code is not creating a new "root" element. The above example just uses the current root node from the existing server.xml and then just appends a new Server element and re-writes the file.

对代码的主要更改不是创建新的“根”元素。上面的示例只使用现有server.xml中的当前根节点,然后只需附加一个新的Server元素并重写该文件。

#2


4  

To append a new data element,just do this...

要附加新数据元素,只需执行此操作...

Document doc = docBuilder.parse(is);        
Node root=doc.getFirstChild();
Element newserver=doc.createElement("new_server");
root.appendChild(newserver);

easy.... 'is' is an InputStream object. rest is similar to your code....tried it just now...

easy ....'is'是一个InputStream对象。休息类似于你的代码....刚刚尝试过...

#3


1  

You can parse the existing XML file into DOM and append new elements to the DOM. Very similar to what you did with creating brand new XML. I am assuming you do not have to worry about duplicate server. If you do have to worry about that, you will have to go through the elements in the DOM to check for duplicates.

您可以将现有XML文件解析为DOM,并将新元素附加到DOM。与您在创建全新XML时所做的非常相似。我假设你不必担心重复的服务器。如果您不必担心这一点,则必须通过DOM中的元素来检查重复项。

DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();

/* parse existing file to DOM */
Document document = documentBuilder.parse(new File("exisgint/xml/file"));

Element root = document.getDocumentElement();

for (Server newServer : Collection<Server> bunchOfNewServers){
  Element server = Document.createElement("server");
  /* create and setup the server node...*/

 root.appendChild(server);
}

/* use whatever method to output DOM to XML (for example, using transformer like you did).*/

#4


0  

If you need to insert node/element in some specific place , you can to do next steps

如果需要在某个特定位置插入节点/元素,则可以执行后续步骤

  1. Divide original xml into two parts
  2. 将原始xml分为两部分
  3. Append your new node/element as child to first first(the first part should ended with element after wich you wanna add your element )
  4. 首先将您的新节点/元素作为子元素添加到第一个(第一部分应该在您想要添加元素之后以元素结束)
  5. Append second part to the new document.
  6. 将第二部分附加到新文档。

It is simple algorithm but should works...

它是简单的算法,但应该工作...

#5


0  

You could use DOM4j doing that.

你可以使用DOM4j来做到这一点。

#1


29  

The following complete example will read an existing server.xml file from the current directory, append a new Server and re-write the file to server.xml. It does not work without an existing .xml file, so you will need to modify the code to handle that case.

以下完整示例将从当前目录中读取现有server.xml文件,附加新服务器并将该文件重新写入server.xml。没有现有的.xml文件它不起作用,因此您需要修改代码来处理这种情况。

import java.util.*;
import javax.xml.transform.*;
import javax.xml.transform.stream.*;
import javax.xml.transform.dom.*;
import org.w3c.dom.*;
import javax.xml.parsers.*;

public class AddXmlNode {
    public static void main(String[] args) throws Exception {

        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = documentBuilder.parse("server.xml");
        Element root = document.getDocumentElement();

        Collection<Server> servers = new ArrayList<Server>();
        servers.add(new Server());

        for (Server server : servers) {
            // server elements
            Element newServer = document.createElement("server");

            Element name = document.createElement("name");
            name.appendChild(document.createTextNode(server.getName()));
            newServer.appendChild(name);

            Element port = document.createElement("port");
            port.appendChild(document.createTextNode(Integer.toString(server.getPort())));
            newServer.appendChild(port);

            root.appendChild(newServer);
        }

        DOMSource source = new DOMSource(document);

        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        StreamResult result = new StreamResult("server.xml");
        transformer.transform(source, result);
    }

    public static class Server {
        public String getName() { return "foo"; }
        public Integer getPort() { return 12345; }
    }
}

Example server.xml file:

示例server.xml文件:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Servers>
  <server>
    <name>something</name>
    <port>port</port>
  </server>
</Servers>

The main change to your code is not creating a new "root" element. The above example just uses the current root node from the existing server.xml and then just appends a new Server element and re-writes the file.

对代码的主要更改不是创建新的“根”元素。上面的示例只使用现有server.xml中的当前根节点,然后只需附加一个新的Server元素并重写该文件。

#2


4  

To append a new data element,just do this...

要附加新数据元素,只需执行此操作...

Document doc = docBuilder.parse(is);        
Node root=doc.getFirstChild();
Element newserver=doc.createElement("new_server");
root.appendChild(newserver);

easy.... 'is' is an InputStream object. rest is similar to your code....tried it just now...

easy ....'is'是一个InputStream对象。休息类似于你的代码....刚刚尝试过...

#3


1  

You can parse the existing XML file into DOM and append new elements to the DOM. Very similar to what you did with creating brand new XML. I am assuming you do not have to worry about duplicate server. If you do have to worry about that, you will have to go through the elements in the DOM to check for duplicates.

您可以将现有XML文件解析为DOM,并将新元素附加到DOM。与您在创建全新XML时所做的非常相似。我假设你不必担心重复的服务器。如果您不必担心这一点,则必须通过DOM中的元素来检查重复项。

DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();

/* parse existing file to DOM */
Document document = documentBuilder.parse(new File("exisgint/xml/file"));

Element root = document.getDocumentElement();

for (Server newServer : Collection<Server> bunchOfNewServers){
  Element server = Document.createElement("server");
  /* create and setup the server node...*/

 root.appendChild(server);
}

/* use whatever method to output DOM to XML (for example, using transformer like you did).*/

#4


0  

If you need to insert node/element in some specific place , you can to do next steps

如果需要在某个特定位置插入节点/元素,则可以执行后续步骤

  1. Divide original xml into two parts
  2. 将原始xml分为两部分
  3. Append your new node/element as child to first first(the first part should ended with element after wich you wanna add your element )
  4. 首先将您的新节点/元素作为子元素添加到第一个(第一部分应该在您想要添加元素之后以元素结束)
  5. Append second part to the new document.
  6. 将第二部分附加到新文档。

It is simple algorithm but should works...

它是简单的算法,但应该工作...

#5


0  

You could use DOM4j doing that.

你可以使用DOM4j来做到这一点。