js访问xml之节点操作

原文出处:http://www.cnblogs.com/Caceolod/articles/1753117.html

获取元素值

x
=xmlDoc.getElementsByTagName("title")[0];
y
=x.childNodes[0];
txt
=y.nodeValue;
结果:txt 
= "Everyday Italian"

获取属性值 
- getAttribute()

xmlDoc
=loadXMLDoc("books.xml");
txt
=xmlDoc.getElementsByTagName("title")[0].getAttribute("lang");
结果:txt 
= "en"

获取属性值 
- getAttributeNode()

x
=xmlDoc.getElementsByTagName("title")[0].getAttributeNode("lang");
txt
=x.nodeValue;

改变文本节点得值

xmlDoc 
= loadXMLDoc("books.xml");
= xmlDoc .getElementsByTagName("title")[0].childNodes[0];
x.nodeValue
="Easy Cooking";

改变属性的值

xmlDoc 
= loadXMLDoc("books.xml");
= xmlDoc .getElementsByTagName("book");
x[
0].setAttribute("category","food");

删除元素节点

xmlDoc 
= loadXMLDoc("books.xml");
= xmlDoc.getElementsByTagName("books")[0];
xmlDoc.documentElement.removeChild(y);

删除自身

xmlDoc 
= loadXMLDoc("books.xml");
= xmlDoc.getElementsByTagName("book")[0];
x.parentNode.removeChild(x);

删除文本节点

xmlDoc 
= loadXMLDoc("books.xml");
= xmlDoc.getElementsByTagName("title")[0];
= x.childNodes[0];
x.removeChild(y);

清空文本节点

xmlDoc 
= loadXMLDoc("books.xml");
= xmlDoc.getElementsByTagName("title")[0];
x.nodeValue 
= ""

根据名称删除属性节点

xmlDoc 
= loadXMLDoc("books.xml");
= xmlDoc.getElementsByTagName("book");
x[
0].removeAttribute('category');

根据对象删除属性节点

xmlDoc 
= loadXMLDoc("books.xml");
= xmlDoc.getElementsByTagName("book");
for(var i=0;i<x.length;i++){
       
while(x[i].attributes.length>0){
                attnode
=x[i].attributes[0];
                old_att
=x[i].removeAttributeNode(attnode);
       }
}
x[
0].removeAttribute(category);

你可能感兴趣的:(js,xml)