Java:XML解析器

Pav*_*van 4 java xml

我有一个类似这样的响应 XML -

<Response> <aa> <Fromhere> <a1>Content</a1> <a2>Content</a2> </Fromhere> </aa> </Response>
Run Code Online (Sandbox Code Playgroud)

我想提取字符串中从<Fromhere>到 的全部内容。</Fromhere>是否可以通过任何字符串函数或 XML 解析器来做到这一点?

请指教。

izb*_*izb 6

您可以尝试使用 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);
Run Code Online (Sandbox Code Playgroud)

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