简体   繁体   English

在Java中将XML文档写入文件时出错

[英]Error writing XML Document to file in Java

I am trying to write org.w3c.dom.Document to a file. 我正在尝试将org.w3c.dom.Document写入文件。 I get the Document from 我得到的Document

String URL = "http://...."
DOMParser parser = new DOMParser();
Document doc = null;
try {
    parser.parse(new InputSource(URL));
    doc = parser.getDocument();
} catch () {}

Then I write this Document to a file using 然后我将此Document写入使用

TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(file));
transformer.transform(source, result);

While doing this I keep getting the following error 在执行此操作时,我不断收到以下错误

ERROR:  'Namespace for prefix 'xlink' has not been declared.'

What might be wrong? 可能是什么问题? Thanks 谢谢

I recommend using a different library such as Dom4J rather than trying to fight your way through the built-in XML API in Java. 我建议使用不同的库(例如Dom4J),而不是尝试通过Java中的内置XML API来解决问题。 Dom4J is better designed and makes your code much more readable: Dom4J设计得更好,并使您的代码更具可读性:

Document doc = new SAXReader().read(inputStream);
new XMLWriter(outputStream).write(doc);

None of this mucking around with FactoryFactoryFactoryFactories . 这些都不能与FactoryFactoryFactoryFactories

I know this doesn't directly answer your question but hopefully it will help anyway. 我知道这不会直接回答您的问题,但希望无论如何都会有所帮助。 Dom4j knows how to talk to the Java XML API so you can mix and match them to suit your needs. Dom4j知道如何与Java XML API对话,因此您可以混合和匹配它们以满足您的需求。 You can even plug it into Xalan or something similar if you want to use XSLT. 如果要使用XSLT,甚至可以将其插入Xalan或类似的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM