【问题标题】:Getting "&lt;" instead of "<" from SOAP response breaks on one device, but not another从 SOAP 响应中获取“<”而不是“<”在一台设备上中断,但在另一台设备上不中断
【发布时间】:2012-09-20 19:47:22
【问题描述】:

我正在发送返回一些 xml 的 SOAP POST。我一直在一个较新的设备(带有 Android 4.1 的 Galaxy Nexus)上进行测试,它运行良好。但是,我只是尝试在旧设备上运行它(运行 Android 2.2 的 HTC Desire HD),我得到了ParseException: At line 1, column 0: unclosed token。以下是相关代码:

String xml = null;
Document doc = null;
String SOAPRequest = "[SOAP REQUEST HERE]";          

HttpPost httppost = new HttpPost("[WEBSITE HERE]");
InputStream soapResponse = null;
try {
    StringEntity postEntity = new StringEntity(SOAPRequest, HTTP.UTF_8);
    postEntity.setContentType("text/xml");
    httppost.setHeader("Content-Type", "application/soap+xml;charset=UTF-8");
    httppost.setEntity(postEntity);

    HttpClient httpclient = new DefaultHttpClient();
    BasicHttpResponse httpResponse = (BasicHttpResponse) httpclient.execute(httppost);

    // Convert HttpResponse to InputStream
    HttpEntity responseEntity = httpResponse.getEntity();
    soapResponse = responseEntity.getContent();
    //// printing response here gives me ...<Result>&lt;blahblahblah&gt;<Result>...

    // Get the SearchResult xml
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = factory.newDocumentBuilder();
    doc = db.parse(soapResponse);

} catch ...

NodeList soapNodeList = doc.getElementsByTagName("Result");
xml = soapNodeList.item(0).getFirstChild().getNodeValue();

//// printing xml here gives me "<" 
return xml;

看一下httpResponse,我感兴趣的部分是这样的:&lt;Result&gt;&amp;lt;blahblahblah&amp;gt;&lt;/Result&gt;

当我尝试使用NodeList 获取此xml 时,&amp;lt;blahblahblah&amp;gl; 变成了字符&lt;

为什么会出现这个问题,我该如何解决?

【问题讨论】:

    标签: android xml parsing dom ascii


    【解决方案1】:

    这可能是相关的:

    android DOM parsing with entities in tags

    ...这导致了:

    http://code.google.com/p/android/issues/detail?id=2607

    ...这似乎表明在早期的 Android 版本中,DOM 解析器无法正确处理实体引用。那里的错误报告讨论了有关如何将实体视为单独的子节点而不是合并到相邻文本节点中的内容,这听起来很奇怪,就像您的情况一样。

    如果这是您遇到的问题,请尝试切换到使用 SAX 解析器。它(恕我直言)也是一个更容易处理的 XML 解析器。

    【讨论】:

    • 谢谢!我将切换到 SAX 解析器。我稍微研究了一下 SAX 与 DOM 并决定使用 DOM,只是因为我似乎必须为 SAX 解析器创建另一个类,而且我很懒……但是我也可以内联吗?只是好奇。
    • 我个人非常喜欢使用 SAX 解析器。考虑到您通过回调获取所有开始标签、字符数据、结束标签等,而且您还必须自己维护一些状态,起初使用起来似乎很痛苦。但我发现它比必须处理遍历 DOM 和处理节点列表等要好得多。我会说 DOM 解析器可能只有在它是一个复杂的 XML 文档和/或你需要随机访问它时才合理.
    • 使用 SAX 的示例是我写的这个 SVG 解析器(还是有点乱):github.com/TrevorPage/TPSVG_Android_SVG_Library/blob/master/… SAX 解析器设置在以 SAXParserFactory spf = SAXParserFactory.newInstance()... 开头的几行中,必要的回调是 @987654325 @、startDocument()startElement()characters().
    • 为了记录,修复了它。而且非常轻松:)
    猜你喜欢
    • 1970-01-01
    • 2011-06-22
    • 2017-05-06
    • 2014-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多