欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

Java 在文档中递归搜索和替换一个节点,java递归,public stati

来源: javaer 分享于  点击 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);                }            }        }    }}
相关栏目:

用户点评