我有XML的小字符串,如:
String myxml = "<resp><status>good</status><msg>hi</msg></resp>";
Run Code Online (Sandbox Code Playgroud)
我想查询以获取其内容.
最简单的方法是什么?
McD*_*ell 36
使用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);
Run Code Online (Sandbox Code Playgroud)
使用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);
Run Code Online (Sandbox Code Playgroud)
使用dom4j,XML处理有点简单.还存在其他几个可比较的XML库.这里讨论 dom4j的替代方案.
以下是如何使用XOM执行此操作的示例:
String myxml = "<resp><status>good</status><msg>hi</msg></resp>";
Document document = new Builder().build(myxml, "test.xml");
Nodes nodes = document.query("/resp/status");
System.out.println(nodes.get(0).getValue());
Run Code Online (Sandbox Code Playgroud)
我更喜欢XOM而不是dom4j,因为它的简单性和正确性.即使您想要,XOM也不会让您创建无效的XML ;-)(例如,在字符数据中使用非法字符)
归档时间: |
|
查看次数: |
34187 次 |
最近记录: |