简体   繁体   中英

How to modify XML with JQuery

I am trying to modify a status flag in an XML structure using Javascript. Using examples found on the internet I believe this should work:

test = "<?xml version='1.0' encoding='utf-8' standalone='no' ?>" + 
    "<resultaat>" +
        "<type>6</type>" +
        "<status>I</status>" +
        "<start_datum>2012-06-16 00:00:00</start_datum>" +
        "<eind_datum></eind_datum>" +
    "</resultaat>"

To change the content of the status field:

$(test).find("status").text("D")

The result is however that test is not modified and still contains the old status I

Thanks for the answers

The correct insight is that you need to convert to an XMLObject first and modify this.

Below is how I ended up doing it:

/* Convert Text to XML Object */
doc = $.parseXML(test)

/* Change the fields required */
$(doc).find('status').text('D')

/* Back to Text */
str = (new XMLSerializer()).serializeToString(doc);

Use jQuery.parseXML()

<p id="someElement"></p>
<p id="anotherElement"></p>

var xml = "<rss version='2.0'><channel><title>RSS Title</title></channel></rss>",
    xmlDoc = $.parseXML( xml ),
    $xml = $( xmlDoc ),
    $title = $xml.find( "title" );

/* append "RSS Title" to #someElement */
$( "#someElement" ).append( $title.text() );

/* change the title to "XML Title" */
$title.text( "XML Title" );

/* append "XML Title" to #anotherElement */
$( "#anotherElement" ).append( $title.text() );

you need to write code something like this...

test = "<?xml version='1.0' encoding='utf-8' standalone='no' ?>" + 
    "<resultaat>" +
        "<type>6</type>" +
        "<status>I</status>" +
        "<start_datum>2012-06-16 00:00:00</start_datum>" +
        "<eind_datum></eind_datum>" +
    "</resultaat>";

def = $(test).find("status").text("D");

console.log(def);

To make it work....

Mmmmm, this answers works... but not allways. I'm using an old webkit version wich is bundled inside Tidesdk and i have some weird problems:

$(xml).find("whatever").append("<however></however>");
// doesn't modify xml

$("<however></however>").appendTo($(xml).find("whatever"));
// does modify xml

??? :_)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM