我有这个 xml 字符串响应(它不是一个 xml 文件,而是一个在请求后显示的 xml),如何获取字段值?例如字段(accountID、contactName...)
<?xml version='1.0' encoding='UTF-8' standalone='no' ?>
<GTSResponse command="dbget" result="success">
<Record table="Account" partial="true">
<Field name="accountID" primaryKey="true"><![CDATA[UsRentcar]]></Field>
<Field name="contactName"><![CDATA[US Car Rental]]></Field>
<Field name="contactPhone"><![CDATA[17864752145]]></Field>
<Field name="contactEmail" alternateKeys="email"><![CDATA[uscarrentr@gmail.com]]></Field>
<Field name="lastLoginTime">1419871821</Field>
<Field name="description"><![CDATA[US Car Rental"]]></Field>
</Record>
</GTSResponse>
最佳答案
您可以使用 Xpath 搜索所有字段并获取值,如下所示:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
String xmlString = ...;
Document xml = builder.parse(new ByteArrayInputStream(xmlString.getBytes()));
XPath xPath = XPathFactory.newInstance().newXPath();
String expression = "/GTSResponse/Record/Field";
NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(xml,
XPathConstants.NODESET);
System.out.println(nodeList);
System.out.println(nodeList.getLength());
for (int i = 0; i < nodeList.getLength(); i++) {
String value = nodeList.item(i).getFirstChild().getNodeValue();
String name = nodeList.item(i).getAttributes().getNamedItem("name")
.toString();
System.out.println(name + ":" + value);
}
此输出:
name="accountID":UsRentcar
name="contactName":US Car Rental
name="contactPhone":17864752145
name="contactEmail":uscarrentr@gmail.com
name="lastLoginTime":1419871821
name="description":US Car Rental"
存储在变量中:
String accountId = nodeList.item(0).getFirstChild().getNodeValue();
String contactName = nodeList.item(1).getFirstChild().getNodeValue();
String contactPhone = nodeList.item(2).getFirstChild().getNodeValue();
String contactEmail = nodeList.item(3).getFirstChild().getNodeValue();
String lastLoginTime = nodeList.item(4).getFirstChild().getNodeValue();
String description = nodeList.item(5).getFirstChild().getNodeValue();
关于java - 向 Web 服务 Opengts 发送 XML 请求以从 Android 应用程序登录时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27732067/