使用 Javascript / Jquery 读取 XML 值



如何使用Javascript或Jquery从下面的XMLstructure中读取专有"d:EncodedAbsUrl"的XML值。(与"m:Properties"相同的问题(。

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

捕获的类型错误:无法读取未定义的属性"m:properties">

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

捕获的类型错误:无法读取未定义的属性"属性">

<?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。

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

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

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

尝试:

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

请参阅 jQuery 选择器转义规则

这可能取决于您获取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 文档的。

使用 JQuery 读取 XML

最新更新