org.w3c.dom.Node的内容如何输出为一个xml文本? 在程序中获得一个org.w3c.dom.Node,如何把它内容输出为一段xml文本,最好同时能格式化。 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 因为node不是一个整体的xml,所以要获得一段xml文本,楼主只能分别去拿它的nodename,value等去拼串的。 先把org.w3c.dom.Node生成一个文件也行啊,然后再用dom4j之类的格式化它。 用xerces的XMLSerializer可以,它可以接受serializer.serialize(org.w3c.dom.Document),而Document可以通过node.getOwnerDocument()获得,再用serializer.setOutputFormat设置一下格式化,就可以输出很漂亮的xml了。done! 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()); } ] 设置transformer的三个属性就可以实现格式化,换行并缩进。 transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); JNI的findclass找不到类 POI无法提取出word2007中的图片吗 如何叫用戶輸入一堆數字,然後吧數目成(*)起來 JList的滚动条添加问题 ★★★★★★★★★分页标签是否只能针对ResultSet分页?★★★★★★★★★★ http://herzberg.ca.sandia.gov/jess/,有没有人可以上去这个网站阿?谢谢 求救,applet不能显示数据库内容? 想学JAVA,请大家介绍基本入门书! 谁能否介绍在jbuilder7下怎么使用structs开发web程序么?谢谢!!!! 各位大侠快救救我吧!!一定给分 ArrayList集合构造函数的疑问 JTable删除行
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());
}
]
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");