`
charyle
  • 浏览: 164631 次
  • 性别: Icon_minigender_1
  • 来自: 天蝎座
社区版块
存档分类
最新评论

JAVA W3C DOM的合并和格式化输出

阅读更多

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

    

public static void combinDocument(Document root,List<Document> targets){
		for(Document d:targets){
			root.getFirstChild().appendChild(
					root.adoptNode(d.getDocumentElement()));
		}		
	}

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

  

public static String toString(Document doc) throws TransformerFactoryConfigurationError, TransformerException{
		 DOMSource source = new DOMSource(doc);
         StringWriter writer = new StringWriter();
         Result result = new StreamResult(writer);
         Transformer transformer = TransformerFactory.newInstance().newTransformer();
         transformer.setOutputProperty(OutputKeys.INDENT, "yes");
         transformer.setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS, "yes");
         transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
         transformer.transform(source, result);
         return (writer.getBuffer().toString());
	}

 

1
0
分享到:
评论
1 楼 axiang0335 2011-12-21  
非常有用,

相关推荐

Global site tag (gtag.js) - Google Analytics