如何在XML中创建新元素?

时间:2014-02-25 11:03:39

标签: java xml dom

我尝试这段代码:

public static void sendXml(String result, int operationN) throws ParserConfigurationException, SAXException, IOException{
        String filepath = "journal.xml";
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        Document doc = docBuilder.parse(filepath);
        doc.getFirstChild();
        doc.getElementsByTagName("command").item(0);
        Element res = doc.createElement("result");
        res.setTextContent(result);
        doc.appendChild(res);
    }

我绝对知道journal.xmlresult一切正常。我有异常HIERARCHY_REQUEST_ERR: An attempt was made to insert a node where it is not permitted at org.apache.xerces.dom.CoreDocumentImpl.insertBefore(Unknown Source) at org.apache.xerces.dom.NodeImpl.appendChild(Unknown Source)。我做错了什么?

我有这样的结构:

 <?xml version="1.0"?>
    <config> 
    <command> Check title (Total posts,Total topics,Total members,Our newest member)
// here i need result
    </command>
    <command> Check login 
    </command>
    </config>

2 个答案:

答案 0 :(得分:1)

您应该最终将新创建的元素附加到文档中:

doc.appendChild(res);

答案 1 :(得分:1)

你可以这样做

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

public class WriteXMLFile {

    public static void sendXml(String result, int operationN) throws Exception, IOException{
        String filepath = "file.xml";
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        Document doc = docBuilder.parse(filepath);

        Node tonode=doc.getElementsByTagName("command").item(0);
        Element res = doc.createElement("result");
        res.setTextContent(result);
        tonode.appendChild(res);
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource source = new DOMSource(doc);
            StreamResult result1 = new StreamResult(new File("file2.xml"));

            // Output to console for testing
             StreamResult result3 = new StreamResult(System.out);

            transformer.transform(source, result1);

            System.out.println("File saved!");
    }

    public static void main(String argv[]) {

      try {
          WriteXMLFile writeXMLFile=new WriteXMLFile();
          writeXMLFile.sendXml("hitest", 1);

      } catch (Exception pce) {
        pce.printStackTrace();
      } 
    }
}

file2.xml

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<config>
    <command>
        Check title (Total posts,Total topics,Total members,Our newest member)
        <result>hitest</result>
    </command>
    <command> Check login
    </command>
</config>
相关问题