user1176926
user1176926

Reputation: 251

Add XML document as child to another node in Javascript

I have a question: I'm getting in Javascript XML. I want to add a 'father' node to that xml. How do I do that?

/* Load the XML text from the text area to a Javascript XML object */
var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = "false";
xmlDoc.loadXML(taData.innerText);
xmlObj = xmlDoc.documentElement;        

/* Creating the Screen node */
var Screen = document.createElement("Screen");
Screen.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
Screen.setAttribute("xsi:noNamespaceSchemaLocation", "../../GUIGenerator_V2/Scheme/GG_Scheme.xsd");

/* Creating the Legend node */
var Legend = document.createElement("Legend");
Legend.setAttribute("EntityType", "Request");

var ImportedNode = document.adopteNode(xmlDoc.documentElement);
Legend.appendChild(ImportedNode);
Screen.appendChild(Legend);

Legend is the child of Screen, And I want to make the xmlDoc a child of Legend.

I have tried to write: Legend.appendChild(xmlDoc.documentElement); but getting an error. What can be the problem?

Upvotes: 0

Views: 2488

Answers (1)

shulard
shulard

Reputation: 603

In some case, a XML is reference as a DOM inside JavaScript so you can use standard DOM functions on it. Pay attention about navigator specific implementation to avoid compatibility problems...

To add a father node you need to use something like :

/* Load the XML text from the text area to a Javascript XML object */
    var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
    xmlDoc.async = "false";
    xmlDoc.loadXML(taData.innerText);
    xmlObj = xmlDoc.documentElement;        

    /* Creating the Screen node */
    var Screen = document.createElement("Screen");
    Screen.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
    Screen.setAttribute("xsi:noNamespaceSchemaLocation", "../../GUIGenerator_V2/Scheme/GG_Scheme.xsd");

    /* Creating the Legend node */
    var Legend = document.createElement("Legend");
    Legend.setAttribute("EntityType", "Request");

    var ImportedNode = document.adopteNode(xmlDoc.documentElement);    
    Legend.appendChild(ImportedNode);
    Screen.appendChild(Legend);

after execution of that code you obtain a document strucured like:

<fathernode>
  <YOURXMLDOCUMENT />
</fathernode>

Upvotes: 1

Related Questions