Christian
Christian

Reputation: 655

remove child nodes from xml with javascript

I'm trying to read from xml file text and remove nodes where that text was. For example I read the text from <en> or <es> nodes and I need to remove those both nodes and save text to <translation>

xml file before editing:

<?xml version="1.0" encoding="UTF-8" ?>
<books>
    <name>
        <translation>
            <en>
                Text 1
            </en>
            <es>
                Text 2
            </es>
        </translation>
    </name>
</books>

So it should looks like this:

<books>
    <translation>
            Text 1
    </translation>
</books>

this is part of my function where after reading text from <en> I'm trying to remove all child nodes from <translation> but I'm stuck and getting an error when I'm using removeChild method

        var lang = 'en';
        $.ajax({
            type: "GET",
            url: 'my.xml',
            dataType: "xml",
            success: function (xml) {
                $(xml).find('translation').each(function () {
                    var text = $(this).find(lang).text();
                });

                $(xml).getElementsByTagName('translation').parentNode.removeChild();
                 // xml convert to json
                    var books = [];
                    var data = $.xml2json(xml)['#document'];
                    that.books = data.books;
                }
            });

I'll appreciate any help. Thank you!

Upvotes: 1

Views: 5654

Answers (3)

John
John

Reputation: 770

var value = [];

$.get("your.xml", function(d){
    values.push($(d).find("en")[0].childNodes[0]);  //push "Text 1" into array
    $(d).find("en").remove();                       //remove node
    $(d).find("es").remove();                       //remove node
    $(d).find("translation").append(values[0]);     //add "Text 1" to node
});

Upvotes: 1

Nathan
Nathan

Reputation: 335

The problem you're running into is that you're attempting to use a jQuery object as a DOM node here:

$(xml).getElementsByTagName('translation').parentNode.removeChild();

To use jQuery, you would do

$(xml).find('translation').remove();

HOWEVER, I think you're possibly headed down a false path. I see you've declared a var text that isn't used anywhere in your code. You probably want to do something like the following:

$xml = $(xml);
$xml.find('translation').each(function () {
    $this = $(this);
    $this.text($this.find(lang).text());
});
// do something with $xml...

I couldn't get xml2json working, as I'm not familiar with that plugin, but it should be relatively straightforward for you.

Upvotes: 1

grexwex
grexwex

Reputation: 35

tried this?

getElementsByTagName('translation').children().remove()

Upvotes: 0

Related Questions