Adding XML DOM elements with jQuery- Is it possible?

别等时光非礼了梦想. 提交于 2019-12-23 21:14:35

问题


I am trying to use jQuery to manipulate the DOM of an XML file I've loaded with ajax. I can select elements, empty them, and remove them, but not add them.

jQuery rarely lets me down, but I am feeling burnt out and defeated. Please help.

The code:

<script type="text/javascript">

$.ajax({
    type: "GET",
    url: "note.xml",
    dataType: "xml",
    success: parseResultsXML
});

function parseResultsXML(xml) {

    $(xml).append('<item>something</item>'); // Nothing gets added! :(
}

</script>

回答1:


I think you will need to use $.parseXML(xml) to parse the XML. parseXML() was new addition to jQuery 1.5. I had similar problem as you, and I ended up using some plugin library to parse XML because I was using jQuery 1.4.

http://api.jquery.com/jQuery.parseXML/

==== Edit ====

It's a bit tricky to manipulate XML using jQuery. Try the following code

var dom = $.parseXML(xml); //returns DOM element
var item = $.parseXML("<item>something</item>"); //returns DOM element

$(dom).children(0).append($(item).children(0))

console.log($(dom).find("item").text()); //should print "something"

You have to do $(dom).children(...) because dom is a document object, you have to wrap it into jQuery in order to use jQuery functions.

You have to do $(dom).children(0).append(...) but not $(dom).append() because dom refers to the document root of the XML DOM tree. recall all DOM looks like:

  Document
     |
    root
  /  |  \   
 c1  c2  c3 ....more children...

So if you do $(dom).append(..) you are actually trying to append to the document root which is not allowed because document root can only have one element child, namely the root element of your xml document.

Similarly, you do .append($(item).children(0)) because you want to insert the root element of item not the document root of item




回答2:


The function parseResultsXML will never be called because of cross domain ajax issues, http://www.w3schools.com/xml/note.xml is in different domain than your page.

Instead copy the xml file to your site and then change the code to:

$.ajax({     
    type: "GET",     
    url: "/note.xml",     
    dataType: "xml",     
    success: parseResultsXML 
}); 


来源:https://stackoverflow.com/questions/6513953/adding-xml-dom-elements-with-jquery-is-it-possible

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!