使用Javascript / Jquery读取XML值

时间:2018-04-08 18:35:51

标签: javascript jquery xml

如何使用Javascript或Jquery从下面的XMLstructure中读取属性“d:EncodedAbsUrl”的XML值。 (与“m:属性”相同)。

尝试

var pics = $(xml).find("entry");
console.log(pics[0].content['\m:properties'].EncodedAbsUrl.innerHTML);
  

未捕获的TypeError:无法读取属性' m:properties'未定义的

var pics = $(xml).find("entry");
console.log(pics[0].content.properties.EncodedAbsUrl.innerHTML);
  

未捕获的TypeError:无法读取属性'属性'未定义的

<?xml version="1.0" encoding="utf-8"?>
<feed xml:base="https://mysharepoint.sharepoint.com/_api/"
    <updated>2018-04-08T17:12:43Z</updated>
    <entry m:etag="&quot;1&quot;">
        <id>12345</id>
        <category term="SP.Data.SlideshowItem" scheme="http://schemas.microsoft.com/ado/2007/08/dataservices/scheme" />
        <link rel="edit" href="Web/Lists(guid'12345')/Items(1)" />
        <title />
        <updated>2018-04-08T17:12:43Z</updated>
        <content type="application/xml">
            <m:properties>
                <d:EncodedAbsUrl>https://GIVE.ME.THIS.URL.:O</d:EncodedAbsUrl>
            </m:properties>
        </content>
    </entry>
    <entry m:etag="&quot;1&quot;">
        <id>123456</id>
        <category term="SP.Data.SlideshowItem" scheme="http://schemas.microsoft.com/ado/2007/08/dataservices/scheme" />
        <link rel="edit" href="Web/Lists(guid'123456')/Items(6)" />
        <title />
        <updated>2018-04-08T17:12:43Z</updated>
        <content type="application/xml">
            <m:properties>
                <d:EncodedAbsUrl>https://GIVE.ME.THIS.URL.:O</d:EncodedAbsUrl>
            </m:properties>
        </content>
    </entry>
</feed>

编辑2018-04-12 我绕过了XML垃圾并将数据作为JSON请求。

3 个答案:

答案 0 :(得分:0)

您应该尝试使用像xml2js这样的开放库来将此XML解析为JSON对象,然后在结构中查找所需的键。示例如下所示

var parseString = require('xml2js').parseString;
var xml = "<root>Hello xml2js!</root>"
parseString(xml, function (err, result) {
    console.dir(result);
});

答案 1 :(得分:0)

当存在像:

这样的特殊字符时,使用转义的jQuery选择器

尝试:

var pics = $(xml).find("entry");
pics.each(function(){
   var url = $(this).find('d\\:EncodedAbsUrl').text();
   console.log(url)
})

请参阅jQuery selector escaping rules

答案 2 :(得分:-1)

这可能取决于您获取XML的方式;即请求,单独文件或设置文件串。如果您要设置文件字符串,则可以执行此操作。

var myXML = "your XML here",
    $xml = $( myXML );  // wrap your xml in jQuery.

   // then you can select the elements like this.
     var $absUrls = $xml.find.("d:EncodedAbsUrl"), // this will return an array of absUrls. 
           $properties = $xml.find("m:Properties"); // this returns an array of m:properties

这是基于jQuery文档。

reading XML WITH JQuery