简体   繁体   中英

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. 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."

//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)"

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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