Java 如何使用 DOM 解析器在此 XML 文件中添加元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20984323/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 05:43:38  来源:igfitidea点击:

How to add an element in this XML file using DOM parser?

javajavascriptxmlparsingdom

提问by user3167333

I want to know how can I modify this XML file,

我想知道如何修改这个 XML 文件,

<?xml version="1.0"?>
<nombre>
    <id>12345</id>
</nombre>

into a XML file like this using DOM parser in Java,

使用 Java 中的 DOM 解析器转换成这样的 XML 文件,

<?xml version="1.0" encoding="UTF-8" ?>
    <heat>2013-09-09</heat>
    <nombre>
      <id>12345</id>
    </nombre>

I have tried this but doesn't work,

我试过这个,但不起作用,

public class Test {

public static final String xmlFilePath = "src/vnx.xml";
public static final String xml2FilePath = "src/input2.xml";

public static void main(String argv[]) {

    try {

        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = documentBuilder.parse(xmlFilePath);

        Element version = document.createElement("heat");
        version.appendChild(document.createTextNode("2013-09-09"));
        document.appendChild(version);



        TransformerFactory transformerFactory = TransformerFactory.newInstance();

        Transformer transformer = transformerFactory.newTransformer();
        DOMSource domSource = new DOMSource(document);

        StreamResult streamResult = new StreamResult(new File(xml2FilePath));
        transformer.transform(domSource, streamResult);


    } catch (ParserConfigurationException pce) {
        pce.printStackTrace();
    } catch (TransformerException tfe) {
        tfe.printStackTrace();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    } catch (SAXException sae) {
        sae.printStackTrace();
    }
}

}

}

It returns a parsing error. Any suggestion would be really helpful. Thanks a lot!

它返回一个解析错误。任何建议都会非常有帮助。非常感谢!

采纳答案by Oomph Fortuity

Try This Code,I have used Xpath to navigate XML and created the new Node and Appended to XML.

试试这个代码,我已经使用 Xpath 来导航 XML 并创建新节点并附加到 XML。

Or Without XPATH you can Do it. Following Code is without Xpath.Xpath Code is in Comment

或者没有 XPATH 你可以做到。以下代码没有 Xpath。Xpath 代码在注释中

 try {
    File inputFile = new File("src/vnx.xml");
    DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    // creating input stream
    Document doc = builder.parse(inputFile );

    //Xpath compiler
    //XPathFactory xpf = XPathFactory.newInstance();
    // XPath xpath = xpf.newXPath();

    //XPath Query
   // XPathExpression expr = xpath.compile("/");
    //Node attributeElement = (Node) expr.evaluate(doc, XPathConstants.NODE);

    //New Node          
    Node childnode=doc.createElement("heat");        
    doc .appendChild(childnode);
    childnode.setTextContent("12-34-56");

    // writing xml file
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    DOMSource source = new DOMSource(doc);
     File outputFile = new File("src/input2.xml");
    StreamResult result = new StreamResult(outputFile );
    // creating output stream
    transformer.transform(source, result);
    } catch (Exception e) {
        e.printStackTrace();
    }

In case file not found,please check the path of your XML files Thank you

如果找不到文件,请检查您的 XML 文件的路径谢谢

回答by Kenma

Before reading your code, I found problems in your XML file.

在阅读您的代码之前,我在您的 XML 文件中发现了问题。

A xml file should contains only one root, in your case, the correct file may be something like this:

一个 xml 文件应该只包含一个根,在你的情况下,正确的文件可能是这样的:

<?xml version="1.0" encoding="UTF-8" ?>
<root>
    <heat>2013-09-09</heat>
    <nombre>
      <id>12345</id>
    </nombre>
</root>

回答by Viraj Dhamal

Try This one:

试试这个:

try {
        DocumentBuilderFactory docFactory = DocumentBuilderFactory
                .newInstance();

        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

        /* create root elements */
        Document doc = docBuilder.newDocument();
        Element rootElement = doc.createElement("root");
        doc.appendChild(rootElement);

        /* create elements */
        Element heat= doc.createElement("Heat");
        heat.setAttribute("heat", "2013-09-09");
        rootElement.appendChild(heat);


        Element number= doc.createElement("number");
        rootElement.appendChild(number);

        /* create child node and add id elements */
        Element id= doc.createElement("ID");
        id.setAttribute("id", "12345");
        number.appendChild(id);


        /* write the content into xml file */
        TransformerFactory transformerFactory = TransformerFactory
                .newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        /* set source and result */
        DOMSource source = new DOMSource(doc);


        StreamResult result = new StreamResult(new File("input2.xml"));

        transformer.transform(source, result);
        return true;
    } catch (ParserConfigurationException pce) {
        LOGGER.error("exception while creating Xml File", pce);
        return false;
    } catch (TransformerException tfe) {
        LOGGER.error("exception while creating Xml File", tfe);
        return false;
    } catch (Exception e) {
        LOGGER.error("exception while creating Xml File", e);
        return false;
    }