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

时间:2014-01-07 23:44:40

标签: java javascript xml parsing dom

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

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

使用Java中的DOM解析器

进入这样的XML文件
<?xml version="1.0" encoding="UTF-8" ?>
    <heat>2013-09-09</heat>
    <nombre>
      <id>12345</id>
    </nombre>

我试过这个但是没有用,

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();
    }
}

}

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

3 个答案:

答案 0 :(得分:1)

尝试此代码,我使用Xpath导航XML并创建新节点并附加到XML。

或者没有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();
    }

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

答案 1 :(得分:0)

在阅读代码之前,我发现XML文件存在问题。

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

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

答案 2 :(得分:0)

试试这个:

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;
    }