Linux安全网 - Linux操作系统_Linux 命令_Linux教程_Linux黑客

会员投稿 投稿指南 本期推荐:
搜索:
您的位置: Linux安全网 > Linux集群 > Architecture > » 正文

Java w3c dom的合并与格式化输出

来源: wenzibenben 分享至:

遇到需要将几个W3C标准的Document文档简单合并,一个主文档,其他的文档并列按照顺序放在主文档的孩子节点上就行了。。。

    

Java代码 
  1. public static void combinDocument(Document root,List<Document> targets){  
  2.         for(Document d:targets){  
  3.             root.getFirstChild().appendChild(  
  4.                     root.adoptNode(d.getDocumentElement()));  
  5.         }         
  6.     }  

  为了便于调试,需要将合并的文档格式化输出,其中主要遇到了缩进的问题。找到个属性,设置下搞定。

  

Java代码 
  1. public static String toString(Document doc) throws TransformerFactoryConfigurationError, TransformerException{  
  2.          DOMSource source = new DOMSource(doc);  
  3.          StringWriter writer = new StringWriter();  
  4.          Result result = new StreamResult(writer);  
  5.          Transformer transformer = TransformerFactory.newInstance().newTransformer();  
  6.          transformer.setOutputProperty(OutputKeys.INDENT, "yes");  
  7.          transformer.setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS, "yes");  
  8.          <span style="color: #ff0000;">transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount""2");</span>  
  9.          transformer.transform(source, result);  
  10.          return (writer.getBuffer().toString());  
  11.     }  

Tags:
分享至:
最新图文资讯
1 2 3 4 5 6
验证码:点击我更换图片 理智评论文明上网,拒绝恶意谩骂 用户名:
关于我们 - 联系我们 - 广告服务 - 友情链接 - 网站地图 - 版权声明 - 发展历史