February 10, 2002 - Adding A Document Fragment to An XML Tree
February 10, 2002 Adding A Document Fragment to An XML Tree Tips: February 2002
Yehuda Shiran, Ph.D.
|
createDocumentFragment()
method. The syntax of the method is:
createDocumentFragment()
Let's look at an example. First, let's read in our mydvd
XML file:
var xmlDoc = new ActiveXObject("Msxml2.DOMDocument");
xmlDoc.async = false;
xmlDoc.load("mydvd.xml");
Now, create the new docFragment
object:
var docFragment = xmlDoc.createDocumentFragment();
The node docFragment
is a container of three elements, elem1
, elem2
, and elem3
. They hold the proceeds from selling soda
, pop-corn
, and snacks
in our mydvd
store. We first create elem1
, and assign its content (proceeds in dollars):
var elem1 = xmlDoc.createElement("soda");
elem1.text = "25393.35";
We insert elem1
to docFragment
using the appendChild()
method:
docFragment.appendChild(elem1);
We repeat these steps for elem2
and elem3
:
var elem2 = xmlDoc.createElement("pop-corn");
elem2.text = "13356.28";
docFragment.appendChild(elem2);
var elem3 = xmlDoc.createElement("snacks");
elem3.text = "356.28";
docFragment.appendChild(elem3);
And finally, we append the new docFragment
node to the DOM
's root:
xmlDoc.documentElement.appendChild(docFragment);
Let's summarize the above calls in one function:
function addDocFragment() {
var xmlDoc = new ActiveXObject("Msxml2.DOMDocument");
var namedNodeMap;
xmlDoc.async = false;
xmlDoc.load("mydvd.xml");
alert(xmlDoc.documentElement.xml);
var docFragment = xmlDoc.createDocumentFragment();
var elem1 = xmlDoc.createElement("soda");
elem1.text = "25393.35";
docFragment.appendChild(elem1);
var elem2 = xmlDoc.createElement("pop-corn");
elem2.text = "13356.28";
docFragment.appendChild(elem2);
var elem3 = xmlDoc.createElement("snacks");
elem3.text = "356.28";
docFragment.appendChild(elem3);
xmlDoc.documentElement.appendChild(docFragment);
alert(xmlDoc.documentElement.xml);
}
Try it now. The first alert box echoed the XML file before adding the document fragment node. The second alert box reflects the addition. Notice the three new elements, <soda>
, <pop-corn>
, and <snacks>
.