Java:XML Parser [英] Java:XML Parser

查看:98
本文介绍了Java:XML Parser的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有类似这样的响应XML -

I have a response XML something like this -

<Response> <aa> <Fromhere> <a1>Content</a1> <a2>Content</a2> </Fromhere> </aa> </Response>

我想从< Fromhere> < / Fromhere> 。可以通过任何字符串函数或XML解析器来实现吗?

I want to extract the whole content from <Fromhere> to </Fromhere> in a string. Is it possible to do that through any string function or through XML parser?

请建议。

推荐答案

您可以尝试使用XPath方法简化XML解析:

You could try an XPath approach for simpleness in XML parsing:

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);

请注意,我还没有尝试过此代码。可能需要调整。

Note that I haven't tried this code. It may need tweaking.

这篇关于Java:XML Parser的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆