Search code examples
javascriptdomxml-parsingjint

Return edited XML string with Javascript


I'm using the the XML for < script > library W3C DOM Parser available here. (This because I'm using js inside a .NET CLI Jint program instead of a browser.)

My problem is, I edit a XML using DOMImplementation.loadXML() function and then I edit one node value, then I want to retrieve as string all the XML including the modified one:

 //instantiate the W3C DOM Parser
 var parser = new DOMImplementation();

 //load the XML into the parser and get the DOMDocument
 var domDoc = parser.loadXML($xmlData);

 //get the root node (in this case, it is ROOTNODE)
 var docRoot = domDoc.getDocumentElement();

 // change "name" element value
 docRoot.getElementsByTagName("name").item(0).nodeValue="John";

 // try to retreive all the XML including the changed one
 $xmlData=docRoot.getXML();

Sample XML:

<name>Carlos</name>

All works good except the last line:

docRoot.getXML();

Which only returns the original XML as string and not the modified one.

Any idea how can I retreive all the XML as string including the modified?


Solution

  • Fixed it replacing:

    docRoot.getElementsByTagName("name").item(0).nodeValue="John";
    

    by:

    docRoot.getElementsByTagName("name").item(0).firstChild.setNodeValue("John");
    

    Seems I needed to call firstChild to text in the Element "name" be really replaced. With this docRoot.getXML() returned all the XML code including the modified one.