java - 向 Web 服务 Opengts 发送 XML 请求以从 Android 应用程序登录时出错

标签 java xml-parsing xsd xmlhttprequest xml-serialization

我有这个 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/

相关文章:

java - JTextArea txt; txt.getText() 跳过 "\n"

java - 如何在 Kotlin 中创建没有访问器的属性?

Python:通过搜索 XML 树将值附加到现有字典条目

将节点添加到根节点时出现 java.lang.NullPointerException

Python:当子属性满足条件时提取XML元素值

java - Windows 2012 Server 用户锁定时 Camel 停止消费

java - Jpanel 元素尺寸过大

xsd - 如何强制生成@XmlSeeAlso 注释?

c# - 架构验证警告和错误

c++ - 从 xsd :extension 获取 C++ 对象