【问题标题】:In Java, how do I parse XML as a String instead of a file?在 Java 中,如何将 XML 解析为字符串而不是文件?
【发布时间】:2010-10-08 09:50:24
【问题描述】:

我有以下代码:

DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(xmlFile);

如何让它解析包含在字符串而不是文件中的 XML?

【问题讨论】:

  • 另请注意javax.xml.parsers.DocumentBuilder.parse(string) 假定字符串是 uri(可怕...)

标签: java xml string file parsing


【解决方案1】:

javadocs 表明 parse 方法被重载了。

使用您的字符串 XML 创建一个 StringStream 或 InputSource 并且您应该进行设置。

【讨论】:

    【解决方案2】:

    一种方法是使用采用 InputSource 而不是文件的 parse 版本

    可以从 Reader 对象构造 SAX InputSource。一个 Reader 对象是 StringReader

    类似

    parse(new InputSource(new StringReader(myString))) may work. 
    

    【讨论】:

      【解决方案3】:

      将字符串转换为 InputStream 并将其传递给 DocumentBuilder

      final InputStream stream = new ByteArrayInputStream(string.getBytes(StandardCharsets.UTF_8));
      DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
      builder.parse(stream);
      

      编辑
      针对 bendin 关于编码的评论,请参阅 shsteimer 对此问题的回答。

      【讨论】:

      • 我更喜欢 StringReader,因为它避免了 String.getBytes(),但这应该通常也可以工作。
      • 当您调用 getBytes() 时,您希望它使用什么编码?你如何告诉 XML 解析器它得到了哪种编码?你希望它猜到吗?当您在默认编码不是 UTF-8 的平台上时会发生什么?
      【解决方案4】:

      我的代码库中有这个功能,这应该适合你。

      public static Document loadXMLFromString(String xml) throws Exception
      {
          DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
          DocumentBuilder builder = factory.newDocumentBuilder();
          InputSource is = new InputSource(new StringReader(xml));
          return builder.parse(is);
      }
      

      另见this similar question

      【讨论】:

      • @shsteimer 我正在传入 xml 字符串,它返回 null。它不会抛出任何异常。一定有什么问题?
      • @sattu:你应该把它作为一个新问题发布。不看你的代码真的很难说。
      • 非常感谢,为我节省了一堆代码,我正在将其转换回文本,但我知道有更好的方法!
      • 如果我有 它返回一个空节点我能做什么?
      • 检查您是否使用了正确的导入语句:import org.xml.sax.InputSource;
      【解决方案5】:

      我正在使用这种方法

      public Document parseXmlFromString(String xmlString){
          DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
          DocumentBuilder builder = factory.newDocumentBuilder();
          InputStream inputStream = new    ByteArrayInputStream(xmlString.getBytes());
          org.w3c.dom.Document document = builder.parse(inputStream);
          return document;
      }
      

      【讨论】:

        【解决方案6】:

        您可以使用 GitHub 上提供的 Scilca XML Progession 包。

        XMLIterator xi = new VirtualXML.XMLIterator("<xml />");
        XMLReader xr = new XMLReader(xi);
        Document d = xr.parseDocument();
        

        【讨论】:

          猜你喜欢
          • 2023-04-11
          • 1970-01-01
          • 1970-01-01
          • 2020-09-28
          • 2023-03-28
          • 2012-09-15
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多