简体   繁体   English

使用Java将节点添加到xml会得到意外的结果吗?

[英]Adding node to xml using java getting unexpected result?

This is my demo.jsp page 这是我的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);

for this i'm getting output as: 为此,我得到的输出为:

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

but expected output is: 但预期输出为:

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

Where should I change the code to get expected result? 我应该在哪里更改代码以获得预期的结果?

To obtain the output: 要获得输出:

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

Where the <welcome> </welcome> element is actually not empty but contains at least one whitespace character, you need to create a text node and add it as the child of the welcome element: 如果<welcome> </welcome>元素实际上不为空,但至少包含一个空格字符,则需要创建一个文本节点并将其添加为welcome元素的子元素:

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

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

element2.appendChild(name);

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

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