我正在使用 REST Web 服务来检索一些数据。作为响应,我得到一些长 xml 或其他文件。例如,它的一部分可能如下所示:
<jfs:jauthRevokeTokenUrl
rdf:resource="https://localhost:9443/jts/jauth-revoke-token" />
<jfs:jauthCheckAuthUrl
rdf:resource="https://localhost:9443/jts/jauth-check-auth" />
<jfs:jauthProxyUrl
rdf:resource="https://localhost:9443/jts/jauth-proxy" />
<jfs:jauthSigninUrl
rdf:resource="https://localhost:9443/jts/jauth-signin" />
如果我现在想要检索节点 jfs:jautSigningURL
的 rdf:resource
值,我可以使用什么 Java 框架来实现此目的?如果响应不是 xml 而是 json 怎么办?那我可以使用什么框架呢?还是我必须自己编写代码?
最佳答案
如果你想避免任何大型框架,你可以看看java中用于解析XML的内置工具
这里是一个示例,假设您有一个 XML
字符串变量
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder db = documentBuilderFactory.newDocumentBuilder();
InputStream inputStream = new ByteArrayInputStream(XML.getBytes());
Document parsed = db.parse(inputStream);
parsed.getDocumentElement().normalize();
Node tag = parsed.getElementsByTagName("jfs:jauthSigninUrl").item(0);
String value = tag.getAttributes().getNamedItem("rdf:resource").getNodeValue();
您可以通过包含 namespace 定义、空检查以及可能使用 XPath 表达式来简化它来进一步完善它,如下所示
XPath xpath = XPathFactory.newInstance().newXPath();
String value = xpath.evaluate("//jauthSigninUrl/@resource", parsed);
参见此处Java XML XPATH
关于java - 使用哪些框架来分析 REST 服务的响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7718436/