簡體   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