生成错误的XML输出

时间:2012-11-30 03:40:11

标签: java xmlhttprequest

附上两张截图和我的代码。我试图将animation_sequence作为结束和结束括号,我已尽力而为,但现在我寻求你的帮助。请帮忙。我的代码将其生成为

代码:

 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document testDoc = builder.parse(new File("./data/sprite_types/" + spriteName + "/" + spriteName + ".xml"));
        Element state = testDoc.createElement("state");
        state.setTextContent(element);
        Element animationState = testDoc.createElement("animation_state");
        Element sequence = testDoc.createElement("animation_sequence");
        testDoc.getElementsByTagName("animations_list").item(0).appendChild(animationState).appendChild(state);
        testDoc.getElementsByTagName("animation_state").item(testDoc.getElementsByTagName("state").getLength() - 1).appendChild(sequence);
        DOMSource source = new DOMSource(testDoc);
        PrintStream ps = new PrintStream("./data/sprite_types/" + spriteName + "/" + spriteName + ".xml");
        StreamResult result = new StreamResult(ps);
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        transformer.transform(source, result);

not good good

1 个答案:

答案 0 :(得分:1)

原因是您正在创建animation_sequence元素,但不在其下创建任何子节点。实际上,您正在创建一个空元素。当序列化为字符串时,空元素将始终显示为<tag/>,而不是<tag></tag>

为避免这种情况,您需要添加一个空的Text节点作为animation_sequence元素的子节点:

sequence.appendChild(testDoc.createTextNode(""));

(或者,如果您使用Commons Lang,请将""替换为StringUtils.EMPTY