繁体   English   中英

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

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

我想知道如何修改这个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();
    }
}

}

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

试试这个代码,我已经使用Xpath导航XML并创建了新的Node并附加到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文件的路径谢谢

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

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

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

试试这个:

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

暂无
暂无

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

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