无法解析没有.xml扩展名的xml

时间:2013-07-25 09:07:38

标签: java android

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

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

同时在网址末尾添加/?format=xml并不能解决问题。

我认为这与获取HttpResponse有关,但我无法解决当前代码的问题。我需要能够检索xml并解析它,即使没有.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以任何方式将一个转换为另一个?

1 个答案:

答案 0 :(得分:0)

正如评论所示,现在您已经在String变量xml中读取了正确的XML。

首先将XML写入文件。

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

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