XML 从 Java 解析服务响应

XML Parsing from Java Rest Service Response

我从 Java 收到以下 XML 回复 休息 Service.Could 任何人如何获得 status 标签信息?

<operation name="EDIT_REQUEST">
<result>
<status>Failed</status>
<message>Error when editing request details - Request Closing Rule Violation. Request cannot be Resolved</message>
</result>
</operation>

粗略的代码在这里

    ByteArrayInputStream input =  new ByteArrayInputStream(
            response.getBytes("UTF-8"));

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(input);

    // first get root tag and than result tag and childs of result tag
    NodeList childNodes = doc.getDocumentElement().getChildNodes().item(0).getChildNodes();
    for(int i = 0 ; i < childNodes.getLength(); i++){
        if("status".equals(childNodes.item(i).getNodeName())){
            System.out.println(childNodes.item(i).getTextContent());
        }
    } 

一种选择是使用 library, imported using ,例如:

compile 'org.jooq:joox:1.3.0'

并像这样使用它:

import org.xml.sax.SAXException;
import java.io.File;
import java.io.IOException;
import static org.joox.JOOX.$;

public class Main {

    public static void main(String[] args) throws IOException, SAXException {
        System.out.println(
                $(new File(args[0])).xpath("/operation/result/status").text()
        );
    }
}

它产生:

Failed

如果您只关心状态文本,用一个简单的带组的正则表达式怎么样?

例如

String responseXml = 'xml response from service....'

Pattern p = Pattern.compile("<status>(.+?)</status>");
Matcher m = p.matcher(responseXml);

if(m.find())
{
   System.out.println(m.group(1)); //Should print 'Failed'
}

XPath 是一种非常强大和直观的快速查询 XML 文档的方法。您可以通过以下步骤达到 status 标记的值。

   DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
   documentBuilderFactory.setNamespaceAware(true);
   DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();
   Document doc = builder.parse(stream); //input stream of response.

   XPathFactory xPathFactory = XPathFactory.newInstance();
   XPath xpath = xPathFactory.newXPath();

   XPathExpression expr = xpath.compile("//status"); // Look for status tag value.
   String status =  expr.evaluate(doc);
   System.out.println(status);