2

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;

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

Simple enough! Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.