I'm using jQuery to edit XML. Yes, I know that's probably a bad idea.
I came across some very strange behavior (a bug?) when using the xml tag <constructor>
. Replacing existing XML with this tag results in the tag being surrounded by 'undefined'.
$(document).ready(function(){
var my_xml = $.parseXML("<document><old>original xml</old></document>");
var new_xml_string = '<constructor>Foobar</constructor>';
var old_node = $(my_xml).find('old');
old_node.replaceWith(new_xml_string);
var my_xml_string = (new XMLSerializer()).serializeToString(my_xml);
console.log(my_xml_string);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
This code works fine for any other tag I try. So far only <constructor>
seems to have this problem.
Any idea what's going on? Is this because jQuery is meant for processing HTML, not XML? Any workarounds I can use?
Your issue appears as replacing xml object
with xml string
.
You should replace xml object
with xml object
.
$(document).ready(function(){
var my_xml = $.parseXML("<document><old>original xml</old></document>");
var new_xml= $.parseXML("<document><constructor>Foo</constructor></document>");
var new_xml_const = $(new_xml).find('constructor');
var old_node = $(my_xml).find('old');
old_node.replaceWith(new_xml_const);
var my_xml_string = (new XMLSerializer()).serializeToString(my_xml);
console.log(my_xml_string);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With