XML解析器 - 无法修改xml

时间:2011-11-05 05:51:41

标签: java xml-parsing

我正在使用代码

测试标准的xml解析器

xml文件是

<? xml version='1.0' encoding='UTF-8'?>
<A></A>

和Java ......

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db=null;
        try {
            db = dbf.newDocumentBuilder();
        } catch (ParserConfigurationException e) {

            e.printStackTrace();
        }
        Document doc=null;
        try {
            doc = (Document) db.parse(filePath);

        } catch (SAXException e) {

            e.printStackTrace();
        } catch (IOException e) {

            e.printStackTrace();
        }

        Element a= (Element) doc.getElementsByTagName("A").item(0);
        Element b=(Element) doc.createElement("B");
        b.setAttribute("id", "12345");
        a.appendChild(b);



                Transformer transformer=null;
        try {
            transformer = TransformerFactory.newInstance().newTransformer();
        } catch (TransformerConfigurationException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (TransformerFactoryConfigurationError e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");

        //initialize StreamResult with File object to save to file
        StreamResult result = new StreamResult(new StringWriter());
        DOMSource source = new DOMSource(doc);
        try {
            transformer.transform(source, result);
        } catch (TransformerException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        String xml= result.getWriter().toString();

...出于某种原因, xml var值始终为

  

[#document:null]

虽然我想得到xml本身:(所以我只是想知道为什么它总是空的?如何获得内部修改的xml来保存它让我们说一个文件?

1 个答案:

答案 0 :(得分:0)

在我的机器上运行 - 你说[#docuument:null]的输出对于文档上的toString是正常的。

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

DocumentBuilder db = dbf.newDocumentBuilder();
ByteArrayInputStream bis = new ByteArrayInputStream(
        "<A></A>".getBytes());
Document doc = db.parse(bis);

Element a = (Element) doc.getElementsByTagName("A").item(0);
Element b = (Element) doc.createElement("B");
b.setAttribute("id", "12345");
a.appendChild(b);

Transformer transformer = TransformerFactory.newInstance()
        .newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");

// initialize StreamResult with File object to save to file
StreamResult result = new StreamResult(new StringWriter());
DOMSource source = new DOMSource(doc);
transformer.transform(source, result);

String xml = result.getWriter().toString();
System.out.println(xml);