Christian
Christian

Reputation: 645

insert values from array into specific node in xml

I'm trying to read xml file and then save some data from it to the array. Then I need to go through array and paste elements to the specific node. For example this is my xml file:

<?xml version="1.0" encoding="UTF-8" ?>
<contact>
  <name>
    <header>
      <de>Hallo</de>
      <en>Hello</en>
    </header>
  </name>
  <name>
    <header>
      <de>Welt</de>
      <en>World</en>
    </header>
  </name>
</contact>

and this what I want to get:

<?xml version="1.0" encoding="UTF-8" ?>
<contact>
  <name>
    <header>
      Hello
    </header>
  </name>
  <name>
    <header>
      World
    </header>
  </name>
</contact>

I have problem when I need to insert into header node array values.

$.ajax({
  type: "GET",
  url: '1.xml',
  dataType: "xml",
  success: function(xml) {
    var values = [];
    $(xml).find('header').each(function() {
      var text = $(this).find(lang).text();
      values.push(text);
    });

    $(xml).find('header').each(function() {
      $(xml).find('de').remove();
      $(xml).find('en').remove();
    });

    // this part where I have problem
    $(xml).find('header').each(function() {
      $.each(values, function(i, val) {
        $(xml).find('header').append(val);
      });
    });
  })
});

Upvotes: 2

Views: 190

Answers (2)

yousef sami
yousef sami

Reputation: 263

Try This :

        $(document).ready(function(){
            var lang="de";
            $.ajax({
                type: "GET",
                url: '1.xml',
                dataType: "xml",
                success: function (xml) {
                    var values = [];
                    $(xml).find('header').each(function () {
                        var text = $(this).find(lang).text();
                        values.push(text);
                    });

                    $(xml).find('header').each(function () {
                        $(xml).find('de').remove();
                        $(xml).find('en').remove();
                    });

                    // Replace the following changes
                    $(xml).find('header').each(function (i) {
                        var nodGen='<'+lang+'>' + values[i] + '</'+lang+'>';
                        $(this).append(nodGen);
                    });

                    // Show new XML
                    alert((new XMLSerializer()).serializeToString(xml));
                }
            });
        });

Upvotes: 1

Quentin Roger
Quentin Roger

Reputation: 6538

You can try this in place of your last loop : ( it will replace the content of the parent (<header>) by the value of (<en>)

 $(xml).find('header en').each(function() {
    $(this).parent().html($(this).html());
 });

Upvotes: 2

Related Questions