【问题标题】:org.w3c.dom.Document to String without javax.xml.transformorg.w3c.dom.Document 到没有 javax.xml.transform 的字符串
【发布时间】:2011-07-27 00:41:30
【问题描述】:

我花了一段时间在 Google 上寻找将 org.w3c.dom.Document 转换为整个 DOM 树的字符串表示的方法,以便我可以将对象保存到文件系统。

但是,我发现的所有解决方案都使用 javax.xml.transform.Transformer,Android 2.1 API 不支持它。如果不使用此类/包含包,我该如何做到这一点?

【问题讨论】:

标签: java android xml string


【解决方案1】:

请试试这个代码:

DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse("/path/to/file.xml");
DOMImplementation domImpl = ownerDocument.getImplementation();
DOMImplementationLS domImplLS = (DOMImplementationLS)domImpl.getFeature("LS", "3.0");
LSSerializer serializer = domImplLS.createLSSerializer();
serializer.getDomConfig().setParameter("xml-declaration", Boolean.valueOf(false));
LSOutput lsOutput = domImplLS.createLSOutput();
lsOutput.setCharacterStream(output);
serializer.write(doc, lsOutput);

【讨论】:

  • 不错,但 org.w3c.tidy.DOMDocumentImpl 不支持。
  • JTidy 没有实现 LSSerializer
【解决方案2】:

为避免使用Transformer,您应该手动迭代您的 xml 树,否则您可以依赖一些外部库。你应该看看here

【讨论】:

    猜你喜欢
    • 2013-04-28
    • 2010-09-07
    • 2012-05-08
    • 2014-04-27
    • 2016-11-25
    • 1970-01-01
    • 2011-09-26
    • 1970-01-01
    • 2018-10-28
    相关资源
    最近更新 更多