小编典典

用Java查询XML的最简单方法

javascript

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

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

我想查询以获取其内容。

最简单的方法是什么?


阅读 366

收藏
2020-09-25

共1个答案

小编典典

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

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);
2020-09-25