如何在Java中保存DOM文档?

时间:2011-03-16 12:20:57

标签: java xml dom xpath document

我正在使用DOM解析器和XPATH来解析我的XML文件。我更改了Document Object中节点的值。但是,当我打开我的XML文件时,它并没有向我显示任何反射。我的DOM解析器代码如下:

private void setPortNumber(int portNumber) {
        try {
        Document parsedDocument = parseDocument(tempPath + "/apache-6/conf/server.xml");
        XPath xPath = XPathFactory.newInstance().newXPath();
        XPathExpression expr;
        expr = (XPathExpression) xPath.compile("//Connector");
        Object result = expr.evaluate(parsedDocument, XPathConstants.NODESET);
        NodeList nodes = (NodeList) result;
        for (int i = 0; i < nodes.getLength(); i++) {
            Node node =nodes.item(i);
            NamedNodeMap attributes = node.getAttributes();
            for(int j=0; j< attributes.getLength(); j++){
                String value = attributes.item(j).getNodeValue();
                if(value.equals("HTTP/1.1")){
                    Node valueNode = attributes.item(0);
                    valueNode.setNodeValue(portNumber+"");
                }
            }
        }
        } catch (XPathExpressionException e) {}
    }
    private Document parseDocument(String xmPath) {
        Document doc = null;
        try {
            DocumentBuilderFactory domFactory = 
                DocumentBuilderFactory.newInstance();
            DocumentBuilder builder;

            builder = domFactory.newDocumentBuilder();

            doc = builder.parse(xmPath);
        }catch (Exception e) {}
        return doc;
    }

完成更改后如何保存文档?

有人可以帮我解决这个问题吗?

3 个答案:

答案 0 :(得分:5)

以下是更新XML文件的示例代码

try
{
  DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
  DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
  Document doc = docBuilder.parse(filePath);
  Node rootNode = doc.getFirstChild();//for getting the root node

  String expersion="books/author";//x-path experssion

  XPathFactory factory = XPathFactory.newInstance();
  XPath xpath = factory.newXPath();
  XPathExpression expr = xpath.compile(expersion);
  Node updateNode=null;
  Object result = expr.evaluate(doc, XPathConstants.NODESET);
  NodeList nodes = (NodeList) result;
  updateNode=nodes.item(0);
  updateNode.appendChild(doc.createCDATASection("new value"));
  TransformerFactory transformerFactory = TransformerFactory.newInstance();
  Transformer transformer = transformerFactory.newTransformer();
  DOMSource source = new DOMSource(doc);
  StreamResult streamResult =  new StreamResult(new File(filePath));
  transformer.transform(source, streamResult);
}
catch (Exception e) {
  e.printStackTrace();
}

答案 1 :(得分:3)

您可以使用Transformer API将DOM写入流或文件。

答案 2 :(得分:2)

您必须使用转换器将dom对象转换为XML。

http://download.oracle.com/javaee/1.4/tutorial/doc/JAXPXSLT4.html

相关问题