Java 正在尝试获取整个XML文件。[#文档:null]错误

Java 正在尝试获取整个XML文件。[#文档:null]错误,java,xml,Java,Xml,我试图在结果中获得完整的XMl(如a…)。但当我执行此代码时,它会在网页上返回[#document:null] 我搜索了[#document:null],发现答案不是错误。但我看不到任何结果 我想看到下图所示的结果 我怎样才能看到它是否成功进行 我对Eclipse是新手。对不起,基本问题! 这是因为doc.toString()返回一个带有[]的字符串。文档上的toString()方法不会将其转换回XML格式。要将文档转换回其XML,您需要一些代码: public static void pri

我试图在结果中获得完整的XMl(如
a…
)。但当我执行此代码时,它会在网页上返回
[#document:null]

我搜索了
[#document:null]
,发现答案不是错误。但我看不到任何结果

我想看到下图所示的结果

我怎样才能看到它是否成功进行

我对Eclipse是新手。对不起,基本问题!


这是因为
doc.toString()
返回一个带有
[]
的字符串。文档上的
toString()
方法不会将其转换回XML格式。要将
文档
转换回其XML,您需要一些代码:

public static void printDocument(Document doc, OutputStream out) throws IOException, TransformerException {
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = tf.newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

    transformer.transform(new DOMSource(doc), 
         new StreamResult(new OutputStreamWriter(out, "UTF-8")));
}
然后调用它以输出文档:

try {
    doc = parseXML(connection.getInputStream());
    response.setCharacterEncoding("UTF-8");

    // OLD CODE
    // PrintWriter out = response.getWriter();
    // out.print(doc.toString());
    // out.close();

    // NEW CODE
    printDocument(doc, response.getOutputStream());
} catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
try {
    doc = parseXML(connection.getInputStream());
    response.setCharacterEncoding("UTF-8");

    // OLD CODE
    // PrintWriter out = response.getWriter();
    // out.print(doc.toString());
    // out.close();

    // NEW CODE
    printDocument(doc, response.getOutputStream());
} catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}