【问题标题】:angularjs load data from xml file and store in a xml objectangularjs 从 xml 文件加载数据并存储在 xml 对象中
【发布时间】:2017-11-03 10:05:46
【问题描述】:

我正在从 XML 文件中读取数据并想使用 angularjs 进行编辑。问题是,$http 调用正在读取数据但将其转换为字符串,无论我是否期望它是对象。我的 XML 数据是:

<?xml version="1.0" encoding="UTF-8"?>
<catalog>
   <book id="bk101">
      <author>Gambardella, Matthew</author>
      <title>XML Developer's Guide</title>
      <genre>Computer</genre>
      <price>44.95</price>
      <check1 version="1"></check1>
      <collection name="argu.ments"/>
      <check3></check3>
      <check4/>
      <acollection name="arguments"/>
      <string name="connect_timeout"></string>
      <publish_date>2000-10-01</publish_date>
      <description>An in-depth look at creating applications 
      with XML.</description>
   </book>
   <book id="bk102">
      <author>Ralls, Kim</author>
      <title>Midnight Rain</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
      <publish_date>2000-12-16</publish_date>
      <description>A former architect battles corporate zombies, 
      an evil sorceress, and her own childhood to become queen 
      of the world.</description>
   </book>  
</catalog>

在 angularjs 中使用以下代码:

$http({
            url: "books.xml",
            method: "GET",          
            headers: {'Content-Type': 'application/xml','charset' : 'utf-8'}
        }).success(function (xml) {
                    console.log(xml);
                    console.log(typeof xml);
        }).error(function () {
                    console.log('error in /writexmlfiletest ');                                         
        });

它在控制台中打印数据,typeof 显示字符串。请帮忙理解。我是否必须转换回 XML 才能执行节点元素操作?

【问题讨论】:

    标签: javascript angularjs xml


    【解决方案1】:

    我们必须将 transformResponse 放入 $http 请求中,如下所示。它将数据解析回xml。

    $http({
                url: "books.xml",
                method: "GET",          
                headers: {'Content-Type': 'application/xml','charset' : 'utf-8'},
                transformResponse : function(data) {
                    // string -> XML document object
                    return $.parseXML(data);
                }
            }).success(function (xml) {
                        console.log(xml);
                        console.log(typeof xml);
            }).error(function () {
                        console.log('error in /writexmlfiletest ');                                         
            });
    

    【讨论】:

      猜你喜欢
      • 2012-07-30
      • 1970-01-01
      • 2023-03-10
      • 1970-01-01
      • 1970-01-01
      • 2021-04-16
      • 1970-01-01
      • 2013-11-30
      • 2018-01-22
      相关资源
      最近更新 更多