【问题标题】:How to create an XML file in Java from scratch?如何从头开始在 Java 中创建 XML 文件?
【发布时间】:2019-06-28 02:41:12
【问题描述】:

我想从头开始创建一个 XML 文件,但我遇到了函数解析问题,我有以下代码。文档说明了这一点:

"abstract Document parse(InputSource is) 解析的内容 给定输入源作为 XML 文档并返回一个新的 DOM 文档 对象。”

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

【问题讨论】:

    标签: java


    【解决方案1】:
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document d = db.parse(new ByteArrayInputStream(string.getBytes()));
    

    这对你有用。您不需要将 InputStream 包装在 InputSource 中,因为这也是一个选项。

    【讨论】:

    • string 是您从中解析文档的任何内容。如果您正在从文件中读取文档,请将字节数组输出流替换为文件流。如果您正在读取示例中的字符串,请将“string”更改为您的变量
    猜你喜欢
    • 2018-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-28
    • 1970-01-01
    • 1970-01-01
    • 2010-09-13
    • 2012-11-30
    相关资源
    最近更新 更多