简体   繁体   English

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

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

I want to create an XML file from scratch and I am having an issue with the function parse, I have the below code. 我想从头开始创建XML文件,而函数解析存在问题,我有以下代码。 The documentation states this: 该文档指出:

"abstract Document parse(InputSource is) Parse the content of the given input source as an XML document and return a new DOM Document object." “抽象文档解析(InputSource是)将给定输入源的内容解析为XML文档,并返回一个新的DOM Document对象。”

//Line with the issue on the parse function
Document document = docBuilder.parse(new InputSource(new StringReader(str)));

An the error that I get is this: " The method parse(InputStream) in the type DocumentBuilder is not applicable for the arguments (InputSource)" 我得到的错误是:“ DocumentBuilder类型的parse(InputStream)方法不适用于参数(InputSource)”

What could be wrong? 有什么事吗 Thanks. 谢谢。

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()));

This will work for you. 这将为您工作。 You don't need to wrap the InputStream in an InputSource, as that's an option as well. 您不需要将InputStream包装在InputSource中,因为这也是一个选择。

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

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