XML - Cargar XML desde un servidor externo

   
Vista:

Cargar XML desde un servidor externo

Publicado por Gangatravel (1 intervención) el 31/07/2015 00:15:17
Hola, me descarge unos ejemplos de prueba para cargar un XML desde otro servidor diferente al mio pero cuando cambio la ruta del XML no me funciona, los archivos que tengo son estos:

HTML:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
<!DOCTYPE html>
<html>
   <head>
   <title>Cross XML Sample</title>
 
   <meta name="viewport" content="width=device-width, initial-scale=1">
 
   <link rel="stylesheet" href="http://code.jquery.com/mobile/1.1.1/jquery.mobile-1.1.1.min.css" />
   <script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
   <script src="http://code.jquery.com/mobile/1.1.1/jquery.mobile-1.1.1.min.js"></script>
   <script src="xml2json.js"></script>
   <script src="jquery.xdomainajax.js"></script>
   <script>
      // For This example, im going to use sample xml from o'reily for practice
      // located at url http://examples.oreilly.com/9780596002527/examples/first.xml
      // We are going to extract character name nodes for this sample 
      function xmlLoader(){
         $.ajax({
             url: 'http://examples.oreilly.com/9780596002527/examples/first.xml',
             dataType: "xml",
             type: 'GET',
             success: function(res) {
               var myXML = res.responseText;
               // This is the part xml2Json comes in.
               var JSONConvertedXML = $.xml2json(myXML);
               $('#myXMLList').empty();
               for(var i = 0; i < JSONConvertedXML.book.character.length; i++){
                  $('#myXMLList').append('<li><a href="#">'+JSONConvertedXML.book.character.name+'</a></li>')
               }
               $('#myXMLList').listview('refresh');
               $.mobile.hidePageLoadingMsg();
             }
         });
      }
 
      $( document ).delegate("#home", "pageshow", function() {
         $.mobile.showPageLoadingMsg();
           xmlLoader();
      });
   </script>
</head>
 
<body>
   <div data-role="page" id="home">
      <div data-role="content">
         <ul data-role="listview" data-theme="c" id="myXMLList">
         </ul>
      </div>
   </div>
</body>
</html>

JS:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
jQuery.ajax = (function(_ajax){
 
    var protocol = location.protocol,
        hostname = location.hostname,
        exRegex = RegExp(protocol + '//' + hostname),
        YQL = 'http' + (/^https/.test(protocol)?'s':'') + '://query.yahooapis.com/v1/public/yql?callback=?',
        query = 'select * from xml where url="{URL}"';
 
    function isExternal(url) {
        return !exRegex.test(url) && /:\/\//.test(url);
    }
 
    return function(o) {
 
        var url = o.url;
 
        if ( /get/i.test(o.type) && !/json/i.test(o.dataType) && isExternal(url) ) {
 
            // Manipulate options so that JSONP-x request is made to YQL
 
            o.url = YQL;
            o.dataType = 'json';
 
            o.data = {
                q: query.replace(
                    '{URL}',
                    url + (o.data ?
                        (/\?/.test(url) ? '&' : '?') + jQuery.param(o.data)
                    : '')
                ),
                format: 'xml'
            };
 
            // Since it's a JSONP request
            // complete === success
            if (!o.success && o.complete) {
                o.success = o.complete;
                delete o.complete;
            }
 
            o.success = (function(_success){
                return function(data) {
 
                    if (_success) {
                        // Fake XHR callback.
                        _success.call(this, {
                            responseText: (data.results[0] || '')
                                // YQL screws with <script>s
                                // Get rid of them
                                .replace(/<script[^>]+?\/>|<script(.|\s)*?\/script>/gi, '')
                        }, 'success');
                    }
 
                };
            })(o.success);
 
        }
 
        return _ajax.apply(this, arguments);
 
    };
 
})(jQuery.ajax);

JS (2):


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
;if(window.jQuery) (function($){
 
 // Add function to jQuery namespace
 $.extend({
 
  // converts xml documents and xml text to json object
  xml2json: function(xml, extended) {
   if(!xml) return {}; // quick fail
 
   //### PARSER LIBRARY
   // Core function
   function parseXML(node, simple){
    if(!node) return null;
    var txt = '', obj = null, att = null;
    var nt = node.nodeType, nn = jsVar(node.localName || node.nodeName);
    var nv = node.text || node.nodeValue || '';
    /*DBG*/ //if(window.console) console.log(['x2j',nn,nt,nv.length+' bytes']);
    if(node.childNodes){
     if(node.childNodes.length>0){
      /*DBG*/ //if(window.console) console.log(['x2j',nn,'CHILDREN',node.childNodes]);
      $.each(node.childNodes, function(n,cn){
       var cnt = cn.nodeType, cnn = jsVar(cn.localName || cn.nodeName);
       var cnv = cn.text || cn.nodeValue || '';
       /*DBG*/ //if(window.console) console.log(['x2j',nn,'node>a',cnn,cnt,cnv]);
       if(cnt == 8){
        /*DBG*/ //if(window.console) console.log(['x2j',nn,'node>b',cnn,'COMMENT (ignore)']);
        return; // ignore comment node
       }
       else if(cnt == 3 || cnt == 4 || !cnn){
        // ignore white-space in between tags
        if(cnv.match(/^\s+$/)){
         /*DBG*/ //if(window.console) console.log(['x2j',nn,'node>c',cnn,'WHITE-SPACE (ignore)']);
         return;
        };
        /*DBG*/ //if(window.console) console.log(['x2j',nn,'node>d',cnn,'TEXT']);
        txt += cnv.replace(/^\s+/,'').replace(/\s+$/,'');
                        // make sure we ditch trailing spaces from markup
       }
       else{
        /*DBG*/ //if(window.console) console.log(['x2j',nn,'node>e',cnn,'OBJECT']);
        obj = obj || {};
        if(obj[cnn]){
         /*DBG*/ //if(window.console) console.log(['x2j',nn,'node>f',cnn,'ARRAY']);
 
                           // http://forum.jquery.com/topic/jquery-jquery-xml2json-problems-when-siblings-of-the-same-tagname-only-have-a-textnode-as-a-child
                           if(!obj[cnn].length) obj[cnn] = myArr(obj[cnn]);
                           obj[cnn] = myArr(obj[cnn]);
 
                           obj[cnn][ obj[cnn].length ] = parseXML(cn, true/* simple */);
         obj[cnn].length = obj[cnn].length;
        }
        else{
         /*DBG*/ //if(window.console) console.log(['x2j',nn,'node>g',cnn,'dig deeper...']);
         obj[cnn] = parseXML(cn);
        };
       };
      });
     };//node.childNodes.length>0
    };//node.childNodes
    if(node.attributes){
     if(node.attributes.length>0){
      /*DBG*/ //if(window.console) console.log(['x2j',nn,'ATTRIBUTES',node.attributes])
      att = {}; obj = obj || {};
      $.each(node.attributes, function(a,at){
       var atn = jsVar(at.name), atv = at.value;
       att[atn] = atv;
       if(obj[atn]){
        /*DBG*/ //if(window.console) console.log(['x2j',nn,'attr>',atn,'ARRAY']);
 
                        // http://forum.jquery.com/topic/jquery-jquery-xml2json-problems-when-siblings-of-the-same-tagname-only-have-a-textnode-as-a-child
                        //if(!obj[atn].length) obj[atn] = myArr(obj[atn]);//[ obj[ atn ] ];
        obj[cnn] = myArr(obj[cnn]);
 
                        obj[atn][ obj[atn].length ] = atv;
        obj[atn].length = obj[atn].length;
       }
       else{
        /*DBG*/ //if(window.console) console.log(['x2j',nn,'attr>',atn,'TEXT']);
        obj[atn] = atv;
       };
      });
      //obj['attributes'] = att;
     };//node.attributes.length>0
    };//node.attributes
    if(obj){
     obj = $.extend( (txt!='' ? new String(txt) : {}),/* {text:txt},*/ obj || {}/*, att || {}*/);
     txt = (obj.text) ? (typeof(obj.text)=='object' ? obj.text : [obj.text || '']).concat([txt]) : txt;
     if(txt) obj.text = txt;
     txt = '';
    };
    var out = obj || txt;
    //console.log([extended, simple, out]);
    if(extended){
     if(txt) out = {};//new String(out);
     txt = out.text || txt || '';
     if(txt) out.text = txt;
     if(!simple) out = myArr(out);
    };
    return out;
   };// parseXML
   // Core Function End
   // Utility functions
   var jsVar = function(s){ return String(s || '').replace(/-/g,"_"); };
 
         // NEW isNum function: 01/09/2010
         // Thanks to Emile Grau, GigaTecnologies S.L., www.gigatransfer.com, www.mygigamail.com
         function isNum(s){
            // based on utility function isNum from xml2json plugin (http://www.fyneworks.com/ - diego@fyneworks.com)
            // few bugs corrected from original function :
            // - syntax error : regexp.test(string) instead of string.test(reg)
            // - regexp modified to accept  comma as decimal mark (latin syntax : 25,24 )
            // - regexp modified to reject if no number before decimal mark  : ".7" is not accepted
            // - string is "trimmed", allowing to accept space at the beginning and end of string
            var regexp=/^((-)?([0-9]+)(([\.\,]{0,1})([0-9]+))?$)/
            return (typeof s == "number") || regexp.test(String((s && typeof s == "string") ? jQuery.trim(s) : ''));
         };
         // OLD isNum function: (for reference only)
         //var isNum = function(s){ return (typeof s == "number") || String((s && typeof s == "string") ? s : '').test(/^((-)?([0-9]*)((\.{0,1})([0-9]+))?$)/); };
 
   var myArr = function(o){
 
            // http://forum.jquery.com/topic/jquery-jquery-xml2json-problems-when-siblings-of-the-same-tagname-only-have-a-textnode-as-a-child
            //if(!o.length) o = [ o ]; o.length=o.length;
    if(!$.isArray(o)) o = [ o ]; o.length=o.length;
 
            // here is where you can attach additional functionality, such as searching and sorting...
    return o;
   };
   // Utility functions End
   //### PARSER LIBRARY END
 
   // Convert plain text to xml
   if(typeof xml=='string') xml = $.text2xml(xml);
 
   // Quick fail if not xml (or if this is a node)
   if(!xml.nodeType) return;
   if(xml.nodeType == 3 || xml.nodeType == 4) return xml.nodeValue;
 
   // Find xml root node
   var root = (xml.nodeType == 9) ? xml.documentElement : xml;
 
   // Convert xml to json
   var out = parseXML(root, true /* simple */);
 
   // Clean-up memory
   xml = null; root = null;
 
   // Send output
   return out;
  },
 
  // Convert text to XML DOM
  text2xml: function(str) {
   // NOTE: I'd like to use jQuery for this, but jQuery makes all tags uppercase
   //return $(xml)[0];
   var out;
   try{
    var xml = ($.browser.msie)?new ActiveXObject("Microsoft.XMLDOM"):new DOMParser();
    xml.async = false;
   }catch(e){ throw new Error("XML Parser could not be instantiated") };
   try{
    if($.browser.msie) out = (xml.loadXML(str))?xml:false;
    else out = xml.parseFromString(str, "text/xml");
   }catch(e){ throw new Error("Error parsing XML string") };
   return out;
  }
 
 }); // extend $
 
})(jQuery);

Alguien sabe que he de cambiar para que cuando cambie la ruta del XML que hay en el codigo html por la del XML que quiero utilizar funcione?
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder
información
Otras secciones de LWP con contenido de XML
- Cursos de XML
- Temas de XML
información
Cursos y Temas de XML
- XHTML, una llamada al orden para el HTML
- Introduccion a XML en Castellano
- Manual de XML