2

I'm currently trying to fill an empty tag of an XML response from an API

<?xml version="1.0" encoding="UTF-8"?>
<prestashop xmlns:xlink="http://www.w3.org/1999/xlink">
    <order>
        <id><![CDATA[1]]></id>
        <shipping_number notFilterable="true"></shipping_number>
        <associations>
            <order_rows nodeType="order_row" virtualEntity="true">
                <order_row>
                    <!-- More tags -->
                </order_row>
            </order_rows>
        </associations>
    </order>
</prestashop>

<!-- I have much more items but they don't matter for what I'm trying to do -->

But I can't edit it.

responseBody.getElementsByTagName("id")[0].childNodes[0].nodeValue = "test"; // Works perfectly
responseBody.getElementsByTagName("shipping_number")[0].childNodes[0].nodeValue = "test"; //  Does not Work

//responseBody being my xml body

Console is telling me that I can't access the value of undefined or null, which makes sense to me but I can't find how to fill shipping_number.

I feel so dumb right now but it's the first time I work on XML files with JavaScript

The only answer I found was to delete the tag and recreate it with its value, but I don't want to believe that you can't edit an empty tag.

Does someone have a solution?

Edit : Thanks to @kjhughes

I managed to do what I wanted:

var cdata = responseBody.createCDATASection('someValue');
responseBody.getElementsByTagName('shipping_number')[0].appendChild(cdata);

1 Answer 1

1

First of all, there's a typo in your XML.

Change

<shipping_number notFilterable="true"></shipping_number

to

<shipping_number notFilterable="true"></shipping_number>
                                                       ^

Now that you've fixed the typo, the next issue is that shipping_number has no children, so

responseBody.getElementsByTagName("shipping_number")[0].childNodes

will be empty. Before you can proceed further, you'll have to add a child node. Contrast this with your other working case where id already has a child, a CDATA node.

To add a child node, use Node.appendChild().

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

2 Comments

oops, that's juste me failing to copy/paste my body, that's not the issue ^^
Thank you very much, I managed to find what I need !! Will edit the post so it's more visible !

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.