繁体   English   中英

如何从头开始用Java创建XML文件?

[英]How to create an XML file in Java from scratch?

我想从头开始创建XML文件,而函数解析存在问题,我有以下代码。 该文档指出:

“抽象文档解析(InputSource是)将给定输入源的内容解析为XML文档,并返回一个新的DOM Document对象。”

//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中,因为这也是一个选择。

暂无
暂无

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

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