我有一个类似这样的响应 XML -
<Response> <aa> <Fromhere> <a1>Content</a1> <a2>Content</a2> </Fromhere> </aa> </Response>
我想从 <Fromhere>
中提取全部内容至 </Fromhere>
在一个字符串中。是否可以通过任何字符串函数或通过 XML 解析器来做到这一点?
请指教。
最佳答案
您可以尝试使用 XPath 方法来简化 XML 解析:
InputStream response = new ByteArrayInputStream("<Response> <aa> "
+ "<Fromhere> <a1>Content</a1> <a2>Content</a2> </Fromhere> "
+ "</aa> </Response>".getBytes()); /* Or whatever. */
DocumentBuilder builder = DocumentBuilderFactory
.newInstance().newDocumentBuilder();
Document doc = builder.parse(response);
XPath xpath = XPathFactory.newInstance().newXPath();
XPathExpression expr = xpath.compile("string(/Response/aa/FromHere)");
String result = (String)expr.evaluate(doc, XPathConstants.STRING);
请注意,我还没有尝试过这段代码。它可能需要调整。
关于Java:XML 解析器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1232377/