如何在javascript中有效地解析xml [英] How to parse xml effectively in javascript

查看:65
本文介绍了如何在javascript中有效地解析xml的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个很大的xml结构.我对如下所示的某些xml结构感兴趣.我只需要提取img标签和src属性的值(如果它们在珊瑚卡中).我试图使用正则表达式来获取带有正则表达式的珊瑚卡封闭标签,然后将正则表达式与珊瑚卡标签一起使用以获取img标签和内容.

I have a big xml structure. I am interested in certain xml structure like below. I need to extract img tags only and the value of the src attribute if they are inside coral-card. I was trying to use regex to get coral-card enclosing tags with a regex and then use regex with the coral-card tags to get to the img tag and the content.

var regex = /<coral\-card ((.|[\r\n])*?)<\/coral\-card>/g;

在获得包含如下所示的珊瑚卡片标签的指定xml内容之后,是否可以使用任何方法?我不想在此之后使用正则表达式,因为我认为应该可以使用jquery或javascript函数获取img标签和src属性值.

Is there a way to use anything after I have got the specified xml content containing coral-card tags like below. I don't want to use regex after this as I think it should be possible to get the img tag and src attribute value using jquery or javascript function.

<coral-card variant="condensed" data-timeline="true" stacked>
    <coral-card-asset>
        <img src="/content/dam/collections/3/3qtVFsGwnDVKpZ6H_SaM/lightbox.folderthumbnail.jpg?width=240&height=240">
    </coral-card-asset>
 </coral-card>

<coral-card variant="semi-condensed" data-timeline="true" stacked>
    <coral-card-asset>
        <img src="/content/dam/collections/3/3qtVFsGwnDVKpZ6H_SaM/small.folderthumbnail.jpg?width=240&height=240">
    </coral-card-asset>
 </coral-card>

推荐答案

DOMParser和xpath用于解析xml非常容易.您可以执行以下操作:

DOMParser and xpath are very easy to use for parsing xml. You can do something like:

const DOMParser = require('xmldom').DOMParser;
const xpath = require('xpath');

let parser = new DOMParser();
let doc = parser.parseFromString(<your xml>);
let document = doc.documentElement;
let coralCards = xpath.select('<path>/coral-card', document);

有关从xml blob中提取节点的所有方法,请参见xpath文档.

See xpath docs for all of the ways you can extract nodes out of an xml blob.

这篇关于如何在javascript中有效地解析xml的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆