在 Java 中查询 XML 的最简单方法

2022-09-02 02:31:03

我有带有XML的小字符串,例如:

String myxml = "<resp><status>good</status><msg>hi</msg></resp>";

我想查询以获取其内容。

最简单的方法是什么?


答案 1

XPath 使用 Java 1.5 及更高版本,无需外部依赖项:

String xml = "<resp><status>good</status><msg>hi</msg></resp>";

XPathFactory xpathFactory = XPathFactory.newInstance();
XPath xpath = xpathFactory.newXPath();

InputSource source = new InputSource(new StringReader(xml));
String status = xpath.evaluate("/resp/status", source);

System.out.println("satus=" + status);

答案 2

使用 dom4j,类似于 McDowell 的解决方案

String myxml = "<resp><status>good</status><msg>hi</msg></resp>";

Document document = new SAXReader().read(new StringReader(myxml));
String status = document.valueOf("/resp/msg");

System.out.println("status = " + status);

使用 dom4j 的 XML 处理稍微简单一些。还有其他几个类似的 XML 库。这里讨论了 dom4j 的替代方案。


推荐