0

我无法从不以 .xml 扩展名结尾的url解析 xml。但是,使用下面的代码,我可以在第一次保存到 /res/raw 时成功解析相同的 xml。

或者,当它使用这样的 .xml 扩展名“api.androidhive.info/pizza/?format=xml”创建时,例如。

同样添加/?format=xml到 url 的末尾也不能解决问题。

我认为这与获取 HttpResponse 有关,但我无法用我当前的代码解决问题。即使没有 .xml 扩展名,我也需要能够检索并解析它。

    public String getXmlFromUrl(String url) {
    String xml = null;

    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        xml = EntityUtils.toString(httpEntity);

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    // return XML
    return xml;
}

public Document getDomElement(String xml){
    Document doc = null;
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    try {

        DocumentBuilder db = dbf.newDocumentBuilder();

        InputSource is = new InputSource();
            is.setCharacterStream(new StringReader(xml));
            doc = db.parse(is); 

        } catch (ParserConfigurationException e) {
            Log.e("Error: ", e.getMessage());
            return null;
        } catch (SAXException e) {
            Log.e("Error: ", e.getMessage());
            return null;
        } catch (IOException e) {
            Log.e("Error: ", e.getMessage());
            return null;
        }

        return doc;
}

这是我的 logcat 的结果:

07-25 17:54:39.090: I/INFO(29276): Content:{"Message":"An error has occurred.","ExceptionMessage":"Value cannot be null.\r\nParameter name: entity","ExceptionType":"System.ArgumentNullException","StackTrace":"   at System.Data.Entity.ModelConfiguration.Utilities.RuntimeFailureMethods.Requires(Boolean condition, String userMessage, String conditionText)\r\n   at System.Data.Entity.DbSet`1.Add(TEntity entity)\r\n   at iisCMS.Controllers.GetAppsController.PostApp(App app)\r\n   at lambda_method(Closure , Object , Object[] )\r\n   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass13.<GetExecutor>b__c(Object instance, Object[] methodParameters)\r\n   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)\r\n   at System.Threading.Tasks.TaskHelpers.RunSynchronously[TResult](Func`1 func, CancellationToken cancellationToken)"}

当我检查来自服务器的响应时,它是application/xml并且我认为我需要text/xml任何方法将一个转换为另一个?

4

1 回答 1

0

如评论所示,现在您已将正确的 XML 读入 String 变量xml

首先将 XML 写入文件。

Path path = new Path("C:/Temp/test.xml");
Files.write(file, xml.getBytes("UTF-8"),
    StandardOpenOption.WRITE | StandardOpenOption.CREATE);

然后,您也可以使用浏览器查看文件是否存在违规行为。DTD、模式、命名空间、验证。

于 2013-07-25T12:59:29.480 回答