2015-09-08 72 views
0

在一个应用程序中,我将一个XML读入org.w3c.dom.Document。然后我搜索我想要删除的特定节点。如何将`org.w3c.dom.Node`转换为`org.w3c.dom.Comment`

<list> 
    <item id="1" /> 
    <item id="2" bad="true"> 
    <item id="2.1" /> 
    </item> 
    <item id="3" /> 
</list> 

目前,我由一个新org.w3c.dom.Comment更换节点包含从替代节点复制了一些关键信息。

<list> 
    <item id="1" /> 
    <!-- removed bad item with id=2 --> 
    <item id="3" /> 
</list> 

但我宁愿将完整的节点及其子结构添加到注释中,以免信息松动。

<list> 
    <item id="1" /> 
    <!-- 
    <item id="2" bad="true"> 
    <item id="2.1" /> 
    </item> 
    --> 
    <item id="3" /> 
</list> 

是否有任何优雅的方法将节点转换为注释,并在稍后的时间点将注释转换回节点?

我现在想到的唯一方法是使用javax.xml.transform.Transformer将节点转换为字符串并将该字符串放入注释元素中。但我认为这会很笨重。

回答

0

您不能直接将某些元素包装到注释中。我认为你应该处理类似如下:

  1. 连载你有一个String要删除的元素,
  2. 插入带有字符串评论获取数据

它可以实现这样,假设你的XML已经以前已在document变量加载(如一个对象org.w3c.dom.Document):

Node e = document.getDocumentElement().getFirstChild(); 

    // final DOMSerializerImpl ds = new DOMSerializerImpl(); 
    final DOMImplementationLS ls = (DOMImplementationLS) document 
     .getImplementation().getFeature("LS", "3.0"); 
    final LSSerializer ser = ls.createLSSerializer(); 
    ser.getDomConfig().setParameter("xml-declaration", false); 

    do { 
    if (e.getNodeType() == Node.ELEMENT_NODE) { 
     final Element el = (Element) e; 
     if ("true".equals(el.getAttribute("bad"))) { 
     // System.out.println("bad!!"); 
     final String sTextReplace = ser.writeToString(el); 
     el.getParentNode().replaceChild(
      document.createComment(sTextReplace), el); 
     } 
     e = e.getNextSibling(); 
    } 
    } while (e != null); 

    document.getDocumentElement().normalize(); 

    System.out.println(ser.writeToString(document)); 

结果此outpu t是:

<list><item id="1"/><!--<item bad="true" id="2"><item id="2.1"/></item>--><item id="3"/></list> 

关于系列化,我花了一些材料here

注意:要小心,如果有评论的元素也包含一些评论...评论不能嵌套。

+0

我曾希望更优雅的东西,但也许这只是它。所以我现在接受这个答案。 – schlac

相关问题