Java评论和取消注释XML文档中的节点

时间:2015-01-13 15:39:23

标签: java xml domdocument

假设我有一个以下的xml结构。我想根据用户输入评论/取消注释一些元素。

<books>
    <book>Java Tutorials and Examples</book>
    <book>Java Tutorials and Examples 1</book>
</books>

输出应该如下。文档createComment对我不起作用。因为它没有取消注释节点,只需将注释放到节点上。

    <books>
        <--<book>Java Tutorials and Examples</book>-->
        <book>Java Tutorials and Examples 1</book>
    </books>

1 个答案:

答案 0 :(得分:1)

这可能会对你有所帮助。它不是动态的,因为您需要在节点名称本身进行编码

public static void main(String[] args) throws Exception {

    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

    // root elements
    Document doc = docBuilder.newDocument();
    Element rootElement = doc.createElement("books");
    doc.appendChild(rootElement);

    Element firstname = doc.createElement("book");
    firstname.appendChild(doc.createTextNode("Java Tutorials and Examples 1"));
    rootElement.appendChild(firstname);

    Element element = doc.getDocumentElement();
    Comment comment = doc.createComment("<book>Java Tutorials and Examples</book>");
    element.getParentNode().insertBefore(comment, element);
    rootElement.insertBefore(comment, firstname);

    prettyPrint(doc);
}

public static final void prettyPrint(Document xml) throws Exception {
    Transformer tf = TransformerFactory.newInstance().newTransformer();
    tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    tf.setOutputProperty(OutputKeys.INDENT, "yes");
    Writer out = new StringWriter();
    tf.transform(new DOMSource(xml), new StreamResult(out));
    System.out.println(out.toString());
}

并创建

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<books>
    <!--<book>Java Tutorials and Examples</book>-->
    <book>Java Tutorials and Examples 1</book>
</books>