0

I'm fetching the following xml file:

<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:g="http://base.google.com/ns/1.0" version="2.0">
    <product>
        <id>1</id>
        <value>2253</value>
    </product>
    <product>
        <id>2</id>
        <value>118</value>
    </product>
    <product>
        <id>3</id>
        <value>111</value>
    </product>
    etc...

My script looks like this :

    var response = UrlFetchApp.fetch(url,options).getContentText();
    var data = XmlService.parse(response);
    var product = doc.getRootElement().getChild("product").getValue();

I'm able to get product values but only for the first item. So for example when trying this var product = doc.getRootElement().getChild("product")[i].getValue(); I got an error.

What can I do to loop through this kind of xml structure?

1 Answer 1

1

You should be using .getChildren("product") instead of .getChild(). The latter returns the first element that matches that node name, whereas .getChildren() returns the array you're trying to loop through.

var products = doc.getRootElement().getChildren("product");
for( var i = 0; i < products.length; i++ ) {
    var product = products[i];
    //enter code here
}
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.