获取XML格式的响应数据

Get Response Data in XML format

本文关键字:响应 数据 格式 XML 获取      更新时间:2023-09-26

我们使用JSON.stringify(oData);获取json格式的数据,如何获取xml格式的数据?

oModel.read('/', null, null, true, function(oData, oResponse){
    var data = JSON.stringify(oData);
    document.write(data );
});

您正在使用OData服务,但是您希望以某种格式响应。对我来说,这只能意味着您想要绕过ODataModel机制为您做的所有工作,并获得OData服务器返回的原始XML。如果是这样的话,我有一个问题和一个答案要问你。

问题:为什么?

答案:如果你真的想从OData响应中获取XML,也就是说,原始的Atom提要通常来自于,比如说,像http://services.odata.org/Northwind/Northwind.svc/Products这样的Northwind实体集,那么你可以在read()方法的成功回调中访问整个HTTP响应对象。将您的问题中的源代码扩展一下,它看起来像这样:

oModel.read('/', null, null, true, function(oData, oResponse){
    document.write(oResponse.body);
});

将产生如下内容:

<feed xml:base="http://services.odata.org/Northwind/Northwind.svc/" xmlns="http://www.w3.org/2005/Atom" xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata">
<id>http://services.odata.org/Northwind/Northwind.svc/Products</id>
<title type="text">Products</title>
<updated>2014-08-26T07:33:36Z</updated>
<link rel="self" title="Products" href="Products"/>
<entry>
<id>http://services.odata.org/Northwind/Northwind.svc/Products(1)</id>
...

但是——你确定你真的想要这个吗?

要获得XML格式的响应,请在odata url中添加$format= XML

参见示例:

  1. http://services.odata.org/Northwind/Northwind.svc/Products? $格式= json
  2. http://services.odata.org/Northwind/Northwind.svc/Products? $ format = xml

要获得XML格式的响应,使用sap.ui.model.xml.XMLModel

oModel.read('/?$format=xml', null, null, true, function(oData, oResponse){
    var xmlDataModel = new sap.ui.model.xml.XMLModel(oData);    
});