简体   繁体   中英

Fill an empty XML tag using JavaScript

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

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() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM