没有javax.xml.transform的org.w3c.dom.Document to String

Kur*_*rru 5 java xml string android

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

但是我发现的所有解决方案都使用javax.xml.transform.Transformer,它不支持作为Android 2.1 API的一部分.如何在不使用此类/包含的情况下执行此操作?

小智 5

请尝试以下代码:

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);
Run Code Online (Sandbox Code Playgroud)


jav*_*nna 3

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