Java 在文档中递归搜索和替换一个节点,java递归,public stati
分享于 点击 30646 次 点评:191
Java 在文档中递归搜索和替换一个节点,java递归,public stati
public static void setTextNode(Node node, String aTagName, String aTagValue){ if(node.getNodeType() == Node.ELEMENT_NODE) { NodeList children = node.getChildNodes(); int numChildren = children.getLength(); if(numChildren == 0) { if(node.getNodeName().equals(aTagName)) { // If there aren't any children but the tag is what we are looking for // add a new text node with the passed value. Document doc = node.getOwnerDocument(); Text txtNode = doc.createTextNode(aTagValue); node.appendChild(txtNode); } } else { // If there are children loop through them for(int i=0; i<numChildren; i++) { Node child = children.item(i); short type = child.getNodeType(); if(type == Node.ELEMENT_NODE) { // If its an element node, recursively call our method to keep looking setTextNode(child, aTagName, aTagValue); } else if(type == Node.TEXT_NODE && node.getNodeName().equals(aTagName)) { // Change the value of this node's text-type child node child.setNodeValue(aTagValue); } } } }}
用户点评