2

I have the following xml.I want to loop through courses for each students.How can this be done using xpath js module of nodejs?

     <students>
        <student>
            <name>George</name>
            <courses>
                <course>
                    <coursename>Philosophy</coursename>
                </course>
                <course>
                    <coursename>Literature</coursename>
                </course>
            </courses>
        </student>
        <student>
            <name>John</name>
            <courses>
                <course>
                    <coursename>History</coursename>
                </course>
                <course>
                    <coursename>Maths</coursename>
                </course>
            </courses>
        </student>
    </students>

1 Answer 1

3

Try this:

var xpath = require('xpath'), 
    dom = require('xmldom').DOMParser
    xml= ".. xml string .."

var doc = new dom().parseFromString(xml)
var nodes = xpath.select("//student", doc)
nodes.forEach(function(node){
    var courses = node.getElementsByTagName('coursename')
    for(var i=0;i< courses.length;i++){
        console.log(node.firstChild.firstChild.nodeValue,courses[i].firstChild.nodeValue)
    }
})
Sign up to request clarification or add additional context in comments.

Comments

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.