How to parse xml effectively in javascript

后端 未结 2 1394
走了就别回头了
走了就别回头了 2021-01-26 11:14

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

相关标签:
2条回答
  • 2021-01-26 11:26

    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);
    

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

    0 讨论(0)
  • 2021-01-26 11:42

    This is exactly why the core DOM specification was created:

    // Find all the <coral-card> elements:
    var elements = document.getElementsByTagName("coral-card");
    
    // Loop through them:
    for(var i = 0; i < elements.length; ++i){
      // Extract whatever you need:
      console.log(elements[i].getAttribute("variant"));
      console.log(elements[i].querySelector("img").src);
    }
    <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>

    0 讨论(0)
提交回复
热议问题