2015-04-18 73 views
1

我有一种情况,我得到了一个XML的字符串表示,我想用SAX解析器解析它。Java SAX解析XML字符串

我知道有一种方法可以使用文档构建器来获取DOM文档并使用DOM解析器解析它,但我想使用SAX解析它。

我不想将它保存到文件中,并使用SAX解析器读取它,除非这是唯一选项。

在这种情况下应该怎么做?

回答

3

使用SAXParser.parse(InputSource is, DefaultHandler dh)其中

InputSource is = new InputSource(new StringReader(str)); 
+0

怎么会是获取字符串作为参数的方法是什么样子?什么会解析返回?你可以请编辑和写作一种方法? – theexplorer

+0

这样的东西:'公共静态文档loadXML(字符串xml)抛出异常 { DocumentBuilderFactory fctr = DocumentBuilderFactory.newInstance(); DocumentBuilder bldr = fctr.newDocumentBuilder(); InputSource insrc = new InputSource(new StringReader(xml)); return bldr.parse(insrc); }' – theexplorer

+0

看到这里https://docs.oracle.com/javase/tutorial/jaxp/sax/parsing.html –