我想从头开始创建一个 XML 文件,但我在函数解析方面遇到问题,我有以下代码。该文档指出:
"abstract Document parse(InputSource is) Parse the content of the given input source as an XML document and return a new DOM Document object."
//Line with the issue on the parse function
Document document = docBuilder.parse(new InputSource(new StringReader(str)));
我得到的错误是这样的:“DocumentBuilder 类型中的方法 parse(InputStream) 不适用于参数 (InputSource)”
可能出了什么问题?谢谢。
private static Document toXmlDocument(String str) throws ParserConfigurationException, SAXException, IOException{
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document document = docBuilder.parse(new InputSource(new StringReader(str)));
return document;
}
public static void main(String[] args) {
try{
String xmlStr = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"+
"<xbrli:xbrl\\n"+
"xmlns:xbrli=\"http://www.xbrl.org/2003/instance\" "+
"xmlns:link=\"http://www.xbrl.org/2003/linkbase\" "+
"xmlns:xlink=\"http://www.w3.org/1999/xlink\"><\n"+
"</xbrli:xbrl>";
Document doc = toXmlDocument(xmlStr);
}
catch(Exception e ){
e.printStackTrace();
}
}
最佳答案
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document d = db.parse(new ByteArrayInputStream(string.getBytes()));
这对你有用。您不需要将InputStream 包装在InputSource 中,因为这也是一个选项。
关于java - 如何在 Java 中从头开始创建 XML 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56800318/