如何从要在xstream中使用的XML Document或Node对象创建InputStream对象?我需要更换???用一些有意义的代码。感谢。
Document doc = getDocument();
InputStream is = ???;
MyObject obj = (MyObject) xstream.fromXML(is);
答案 0 :(得分:46)
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
Source xmlSource = new DOMSource(doc);
Result outputTarget = new StreamResult(outputStream);
TransformerFactory.newInstance().newTransformer().transform(xmlSource, outputTarget);
InputStream is = new ByteArrayInputStream(outputStream.toByteArray());
答案 1 :(得分:5)
如果您使用的是没有任何第三方库的Java,则可以使用以下代码创建InputStream
:
/*
* Convert a w3c dom node to a InputStream
*/
private InputStream nodeToInputStream(Node node) throws TransformerException {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
Result outputTarget = new StreamResult(outputStream);
Transformer t = TransformerFactory.newInstance().newTransformer();
t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
t.transform(new DOMSource(node), outputTarget);
return new ByteArrayInputStream(outputStream.toByteArray());
}
答案 2 :(得分:2)
一种方法:使用Source将Document
调整为DOMSource。创建StreamResult以适应ByteArrayOutputStream。使用Transformer中的TransformerFactory.newTransformer复制数据。检索您的byte[]
并使用ByteArrayInputStream进行投放。
将代码放在一起留作练习。
答案 3 :(得分:2)
public static InputStream document2InputStream(Document document) throws IOException {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
OutputFormat outputFormat = new OutputFormat(document);
XMLSerializer serializer = new XMLSerializer(outputStream, outputFormat);
serializer.serialize(document);
return new ByteArrayInputStream(outputStream.toByteArray());
}
如果你使用的是apache Xerces实现,你也可以使用输出格式设置format参数。
答案 4 :(得分:1)
public static InputStream documentToPrettyInputStream(Document document) throws IOException{
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
XMLWriter xmlWriter = new XMLWriter(outputStream, OutputFormat.createPrettyPrint());
xmlWriter.write(document);
xmlWriter.close();
InputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
return inputStream;
}
如果你碰巧使用DOM4j,你需要打印漂亮!