1

I'm using jQuery.

$.ajax({
   url: xxx,
   success: function(data) {
      ...
   }
});

The data is an XML document like:

<root>
   <source>
      <a><source>...</source></a>
      <b>...</b>
      ...
   </source>
   <article>
   ...
   </article>
</root>

I want to extract the XML fragment under source tag, and append them to a div with id "converted". How could I do? PS: the fragment may include source tags too.

4
  • What did you try? what happened? Where did you get stuck? Did you look at other questions (randomly, like this one: stackoverflow.com/questions/8498098/… ) Commented Dec 18, 2013 at 9:10
  • There is nothing for AJAX here in particular. You should look for parse XML using JavaScript or JQuery. Something like stackoverflow.com/q/7228141/1654121 Commented Dec 18, 2013 at 9:12
  • @Nanne, I don't know howto handle data. I've tried $(data), but it does not work as I expected. I mean I don't know howto do next with $(data). I mentioned ajax, because data is returned from ajax, and it seems like it's the XMLDocument type. Commented Dec 18, 2013 at 9:12
  • @theghostofc I'll try parseXML. Commented Dec 18, 2013 at 9:13

3 Answers 3

1

Try this:

$('#converted').append($('source:first', data));
Sign up to request clarification or add additional context in comments.

1 Comment

It works! Thanks every body! $('source:first', data), that's what I'm looking for!
0
var txt = data
if (window.DOMParser)
{
    parser = new DOMParser();
    xmlDoc = parser.parseFromString(txt, "text/xml");
}
else // Internet Explorer
{
    xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
    xmlDoc.async = false;
    xmlDoc.loadXML(txt); 
}

var array_of_source_elems = xmlDoc.getElementsByTagName("source");

xmlDoc can then be used like DOM Documents e.g.: xmlDoc.getElementsBy... etc.

5 Comments

Thank you for your answer. But would you please give me a jquery example? I prefer jquery.
xmlDoc = $.parseXML( data ), $xml = $( xmlDoc ), $source_tags = $xml.find( "source" );
It seems that your solution is same as @Atropo . But I failed.
Do you properly included jquery js file? try to debug with console.log(xmlDoc)
Yeah, jquery is included properly, because other functions run well. The console output is Object: context, jquery, and some functions.
0

if you are getting XML documents from ajax, try this

Documentation & Source: https://github.com/josefvanniekerk/jQuery-xml2json

$.get('data/temp.xml', function(xml) {
          var jObj = $.xml2json(xml);
          alert(jObj.node.node1.name[0]["Hello"]);
    });

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.