[英]XML Parsing from Java Rest Service Response
I am getting the below XML response from Java Rest Service.Could any one how to get status tag information? 我从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>
A rough code is here 大致的代码在这里
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());
}
}
If you are just concerned with the status text, how about just having a simple regex with a group? 如果您只关心状态文本,那么仅使用带有组的简单正则表达式呢?
eg 例如
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
is a very robust and intuitive way to quickly query XML documents. XPath
是一种非常健壮和直观的方法,可以快速查询XML文档。 You can reach value of status
tag by following steps. 您可以按照以下步骤达到
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);
One option is to use the joox library, imported using gradle , like: 一种选择是使用joox库,采用进口的gradle产出 ,如:
compile 'org.jooq:joox:1.3.0'
And use it like: 并像这样使用它:
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()
);
}
}
It yields: 它产生:
Failed
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.