更改xml标记的值

时间:2011-06-10 08:24:14

标签: java xml doc

我有一个文件org.w3c.dom.Document,我想替换xml中的特定标签的值。我试过以下但不知何故它不起作用。它不会给出错误但我看不到值的变化

org.w3c.dom.Document中

public boolean SetTextInTag(Document doc, String tag, String nodeValue)
    {
        Node node = getFirstNode(doc, tag);
        if( node != null){
            node.setNodeValue(nodeValue);
            return true;
           }
         return false;
   }

EG

 <mytag> this value is to be changed </mytag>

我希望将标记值修改为nodeValue。我的代码不会给出任何错误但我看不到值的变化。

4 个答案:

答案 0 :(得分:4)

尝试使用node.setTextContent(nodeValue)代替node.setNodeValue(nodeValue)

答案 1 :(得分:2)

在节点上使用setNodeValue来更改它的值将起作用,但前提是它只是一个Text节点。很有可能,在不是文本节点的节点上调用setNodeValue方法。实际上,您的代码可能正在修改Element节点,因此没有任何结果。

为了进一步解释,您的文件是:

<mytag> this value is to be changed </mytag>

实际上被解析器视为:

Element (name = mytag, value = null)
  - TextNode (name = #text, value= " this value is to be changed ")

元素节点的值始终为null,因此在它们上设置值不会修改子文本节点的值。使用其中一个答案中建议的setTextContent将起作用,因为它会修改TextNode的值而不是Element。

您也可以使用setNodeValue更改值,但仅在检测到节点是否为TextNode之后:

if (node != null && node.getNodeType() == Node.TEXT_NODE) {
    node.setNodeValue(nodeValue);
    return true;
}

答案 2 :(得分:1)

您需要编写xml文件以查看更改。你这样做了吗?

节点的价值不一定是您认为的。看看这里的表格: documentation

您最好将replaceChild功能用于您的目的。那是

Node newChild = document.createTextNode("My new value");
Node oldChild = // Get the child you want to replace...
replaceChild(newChild, oldChild);

请记住,您要替换的是一个文本节点,它是您刚刚查找的标记的子节点。很可能,Node oldChild = node.getFirstChild;正是您所寻找的。

答案 3 :(得分:0)

查看此代码......可能会帮助你。

<folks>
<person>
    <name>Sam Spade</name>
    <email>samspade@website.com</email>
</person>
<person>
    <name>Sam Diamond</name>
    <email>samdiamond@website.com</email>
</person>
<person>
    <name>Sam Sonite</name>
    <email>samsonite@website.com</email>
</person>
</folks>

以下是解析和更新节点值的代码......

public void changeContent(Document doc,String newname,String newemail) {
Element root = doc.getDocumentElement();
NodeList rootlist = root.getChildNodes();
for(int i=0; i<rootlist.getLength(); i++) {
    Element person = (Element)rootlist.item(i);
    NodeList personlist = person.getChildNodes();
    Element name = (Element)personlist.item(0);
    NodeList namelist = name.getChildNodes();
    Text nametext = (Text)namelist.item(0);
    String oldname = nametext.getData();
    if(oldname.equals(newname)) {
        Element email = (Element)personlist.item(1);
        NodeList emaillist = email.getChildNodes();
        Text emailtext = (Text)emaillist.item(0);
        emailtext.setData(newemail);
    }
} 
}
相关问题