我从Java Rest Service获得以下XML响应。是否可以获取状态标记信息?
<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>
答案 0 :(得分:1)
粗略的代码在这里
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());
}
}
答案 1 :(得分:1)
如果你只关心状态文本,那么只需要一个简单的正则表达式与组合如何?
e.g。
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'
}
答案 2 :(得分:1)
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);
答案 3 :(得分:-1)
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