使用java将节点添加到xml获得意外结果?

时间:2014-05-21 00:01:18

标签: java xml xmlnode

这是我的demo.jsp页面

String filename = "TestNode.xml";
ServletContext app = getServletContext();
String projectPath = app.getRealPath("/");
String result = projectPath + filename;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setValidating(false);
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new FileInputStream(new File(result)));
Element rootElement = doc.getDocumentElement();
Element element1 = doc.getDocumentElement();
Element element2 = doc.createElement("hai");
rootElement.appendChild(element2);
Element name = doc.createElement("welcome");
element2.appendChild(name);
element1.appendChild(element2);
DOMSource src = new DOMSource(doc);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = null;
transformer = transformerFactory.newTransformer();
StreamResult rslt = new StreamResult(result);
transformer.transform(src, rslt);

为此我输出为:

<root>    
    <hai>
        <welcome/>
    </hai>
</root>

但预期输出为:

<root>    
    <hai>
        <welcome>
        </welcome>
    </hai>
</root>

我应该在哪里更改代码以获得预期结果?

1 个答案:

答案 0 :(得分:0)

获取输出:

<root>    
    <hai>
        <welcome>
        </welcome>
    </hai>
</root>

<welcome> </welcome>元素实际上不是空的但至少包含一个空格字符,您需要创建一个文本节点并将其添加为welcome元素的子元素:

Element name = doc.createElement("welcome");

Node textNode = doc.createTextNode(" ");
name.appendChild(textNode);

element2.appendChild(name);