在Java中解析XML字符串的最佳方法?

我正在使用javax.xml.parsers.DocumentBuilder在Java中解析字符串。 但是,没有直接解析String的函数,所以我这样做:

 public static Document parseText(String zText) { try { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(new InputSource(new StringReader(zText))); doc.getDocumentElement().normalize(); return doc; } catch (Exception e) { e.printStackTrace(); } return null; } 

这是最好的方法吗? 我觉得必须有一个更简单的方法……谢谢!

直接回答你的问题 – 据我所知,没有更好的方法。 使用输入源是因为它更通用,可以处理来自文件,字符串或线路的输入是我的理解。

您也可以尝试使用SAX Xml解析器 – 它更基本,并使用访问者模式,但它完成了工作,对于小型数据集和简单的XML模式,它非常容易使用。 SAX也包含在核心JRE中。

我个人更喜欢dom4j 。 看看他们的快速入门,很简单。

如果我赶时间或者我不在乎,我就不会正常化。 您可以在需要时将节点标准化。

我同意aperkins ,这是我的javax助手:

 /** * Returns a {@code Document} from the specified XML {@code String}. * * @param xmlDocumentString a well-formed XML {@code String} * @return a {@code org.w3c.dom.Document} */ public static Document getDomDocument(String xmlDocumentString) { if(StringUtility.isNullOrEmpty(xmlDocumentString)) return null; InputStream s = null; try { s = new ByteArrayInputStream(xmlDocumentString.getBytes("UTF-8")); } catch(UnsupportedEncodingException e) { throw new RuntimeException("UnsupportedEncodingException: " + e.getMessage()); } return XmlDomUtility.getDomDocument(s); } 

这个助手取决于另一个:

 /** * Returns a {@code Document} from the specified {@code InputStream}. * * @param input the {@code java.io.InputStream} * @return a {@code org.w3c.dom.Document} */ public static Document getDomDocument(InputStream input) { Document document = null; try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder builder = factory.newDocumentBuilder(); document = builder.parse(input); } catch(ParserConfigurationException e) { throw new RuntimeException("ParserConfigurationException: " + e.getMessage()); } catch(SAXException e) { throw new RuntimeException("SAXException: " + e.getMessage()); } catch(IOException e) { throw new RuntimeException("IOException: " + e.getMessage()); } return document; } 

更新:这些是我的导入:

 import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.xml.sax.SAXException; 

您可以尝试的另一个选项是Castor,我认为它使事情变得如此简单:

http://www.castor.org/