1. ホーム
  2. Web制作
  3. XML/XSLT

javascriptでxmlを操作するための方法と技術

2022-01-15 01:56:52


コピーコード
コードは以下の通りです。
<script language="JavaScript">
<! --
var doc = new ActiveXObject("Msxml2.DOMDocument"); //ie5.5+,CreateObject("Microsoft.XMLDOM")
//load the document
//doc.load("b.xml");
//create document header
var p = doc.createProcessingInstruction("xml","version='1.0' encoding='gb2312'");
//Add a file header
doc.appendChild(p);
//used to get the root contact when loading directly
//var root = doc.documentElement;
//Two ways to create a root contact
// var root = doc.createElement("students");
var root = doc.createNode(1,"students","");
//create child contacts
var n = doc.createNode(1,"ttyp","");
//Specify the text of the child contact
//n.text = " this is a test";
//create the Sun contact
var o = doc.createElement("sex");
o.text = "male"; //specify its text
//create the attribute
var r = doc.createAttribute("id");
r.value="test";
//Add properties
n.setAttributeNode(r);
// Create a second attribute
var r1 = doc.createAttribute("class");
r1.value="tt";
//Add the attribute
n.setAttributeNode(r1);
//Remove the second attribute
n.removeAttribute("class");
// Add the Sun contact
n.appendChild(o);
//add a text splice
n.appendChild(doc.createTextNode("this is a text node."));
//add annotation
n.appendChild(doc.createComment("this is a comment\n"));
//add child contact
root.appendChild(n);
//Copy the contact
var m = n.cloneNode(true);
root.appendChild(m);
//delete the contact
root.removeChild(root.childNodes(0));
// Create data segments
var c = doc.createCDATASection("this is a cdata");
c.text = "hi,cdata";
//add data fields
root.appendChild(c);
//add the root contact
doc.appendChild(root);
//Find the contact
var a = doc.getElementsByTagName("ttyp");
//var a = doc.selectNodes("//ttyp");
//Display the properties of the change contact
for(var i= 0;i<a.length;i++)
{
alert(a[i].xml);
for(var j=0;j<a[i].attributes.length;j++)
{
alert(a[i].attributes[j].name);
}
}
//modify the node, use XPATH to locate the node
var b = doc.selectSingleNode("//ttyp/sex");
b.text = "female";
//alert(doc.xml);
//XML save (need to be on server side, client use FSO)
//doc.save();
//View root contact XML
if(n)
{
alert(n.ownerDocument.xml);
}
//-->
</script>