Angel Cuenca
Angel Cuenca

Reputation: 1659

Iterate XML tags in Javascript

I have a var with the content that is shown in the bottom. The idea is iterate over this var and get the content betwen <module> and </module> tags and insert it into array var.

<module>
    <title>Tag1</title>
    <multipleChoice>
        <option>option 1</option>
    </multipleChoice>
</module>
<module>
    <title>Tag2</title>
    <multipleChoice>
        <option>option 1</option>
        <option>option 2</option>
    </multipleChoice>
</module>
<module>
    <title>Tag4</title>
    <multipleChoice>
        <option>option 1</option>
        <option>option 2</option>
    </multipleChoice>
</module>

So this array var is going to save in the [0] position and so on:

 <module>
    <title>Tag1</title>
    <multipleChoice>
        <option>option 1</option>
    </multipleChoice>
</module>

What I have tried so far is getting each module tag in this way and insert into each array position. I have read about xmlDoc Parser but not sure if it's the best approach to do this.

//Get module section xml
var array = [];
var startPos = str.indexOf("<module>");
var endPos = str.indexOf("</module>");
var xmlModule = str.substring(startPos,endPos).trim();

array[0] = xmlModule;

Upvotes: 2

Views: 70

Answers (1)

kukkuz
kukkuz

Reputation: 42352

You can use DOMParser to parse the string to a valid DOM element

  1. Create a root (any name for that matter) element for making it parseable.

  2. Loop through the modules and get the array as desired.

See demo below:

var parser = new DOMParser();
var xml = `<root>
<module>
    <title>Tag1</title>
    <multipleChoice>
        <option>option 1</option>
    </multipleChoice>
</module>
<module>
    <title>Tag2</title>
    <multipleChoice>
        <option>option 1</option>
        <option>option 2</option>
    </multipleChoice>
</module>
<module>
    <title>Tag4</title>
    <multipleChoice>
        <option>option 1</option>
        <option>option 2</option>
    </multipleChoice>
</module>
</root>`;
var xmlDoc = parser.parseFromString(xml,"text/xml");

var result = Array.prototype.map.call(
xmlDoc.querySelectorAll('module'), function(e){
  return e.outerHTML.replace(/\s/g, '');
});

console.log(result);

Upvotes: 3

Related Questions