XML DOM节点操作总结

XML文件中一切成分都可以看做节点,最常见的3中节点类型是:元素节点,属性节点,文本节点
注意:元素的属性节点并不是元素的子节点,通过node.getAttributeNode("attrName")获得,元素里的文本是元素的子节点
--------------------------------------------------------------------------
XML DOM属性:
x.nodeType (元素节点1 属性节点2 文本节点3  注释节点8 文档节点9 xmldoc.documentElement..)
x.nodeName (#text #document 标签名 属性名..)
x.nodeValue (null,属性值,文本)
x.parentNode
x.childNodes,x.firstChild, x.lastChild
x.attributes 元素的属性节点的集合 x.attributes.length,  x.attributes.getNamedItem(attr)

XML DOM方法:
x.getElementsByTagName(tag)
x.appendChild(node)
x.removeChild(node)
----------------------------------------------------------------
节点的访问
1.根据标签名,无视文档结构如何  xmlDoc.getElementsByTagName(tag)
2.根据文档结构,节点间的关系来访问 parentNode,childNodes,firstChild,lastChild,previousSibling,nextSibling

x=xmlDoc.getElementsByTagName("book")[0].attributes
x.getNamedItem("author");
x.length
--------------------------------------------------------------------------
节点的修改
文本节点: textNode.nodeValue="changeit";
属性节点: eleNode.setAttribute("author","rolin");   attrNode.nodeValue=...
var attrNode=eleNode.getAttributeNode("author");
attrNode.nodeValue="rolin";
元素节点: appendChild, removeChild
--------------------------------------------------------------------------
节点的删除
removeChild(node);
x.parentNode.removeChild(x); //删除自身

删除元素节点和文本节点都用 removeChild() , 因为元素节点和文本节点一般都是父子关系
删除属性节点:removeAttribute(attrName) , removeAttributeNode(attrnode)

eleNode.removeAttribute("author")
var attrNode=eleNode.getAttributeNode("author");
eleNode.removeAttributeNode(attrNode);
--------------------------------------------------------------------------
节点的替换
替换元素节点/文本节点:replaceChild(newNode,oldNode)
替换文本节点中的数据:replaceData(offset,length,newString); textNode.replaceData(0,8,'hello'); textNode.nodeValue="newstringdata";
替换属性节点: eleNode.setAttribute("author","marktwin"); ele.setAttributeNode(attrNode)
--------------------------------------------------------------------------
创建节点
创建元素节点:xmlDoc.createElement(tag);
创建属性节点:xmlDoc.createAttribute(attr);
创建文本节点: xmlDoc.createTextNode(str);
创建文本片段: xmlDoc.createCDATASection(str)
创建注释节点: xmlDoc.createComment(str)
--------------------------------------------------------------------------

添加节点
添加元素节点:
eleNode.appendChild(node);
eleNode.insertBefore(newNode,refNode);
添加属性节点:
eleNode.setAttribute(attr)
文本节点添加文本
txtNode.insertData(str)

--------------------------------------------------------------------------
克隆节点:
node.cloneNode(true)
node.cloneNode(false)

--------------------------------------------------------------------------

原文地址:https://www.cnblogs.com/stephenykk/p/3109539.html