Java 更改xml标记的值

Java 更改xml标记的值,java,xml,doc,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)

我有一个文档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;
   }
乙二醇

要更改此值

我希望将标记值更改为nodeValue。我的代码没有给出任何错误,但我看不到值的更改。

您需要写出xml文件才能看到更改。你会那样做吗

节点的值不一定是您认为的值。请看下面的表格:

出于您的目的,您最好使用
replaceChild
函数。就是

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

请记住,您试图替换的是一个文本节点,它是您刚刚查找的标记的子节点。很可能,
Node oldChild=Node.getFirstChild就是您要查找的。

尝试
节点。setTextContent(nodeValue)
而不是
节点。setNodeValue(nodeValue)
查看此代码。。。也许能帮你

<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>

斯佩德
samspade@website.com
山姆·戴蒙德
samdiamond@website.com
萨姆·索尼特
samsonite@website.com
下面是解析和更新节点值的代码

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);
    }
} 
}
公共作废更改内容(文档文档、字符串newname、字符串newemail){
元素根=doc.getDocumentElement();
NodeList rootlist=root.getChildNodes();

对于(int i=0;i在节点上使用
setNodeValue
更改其值将起作用,但仅当它是文本节点时才起作用。很可能是在不是文本节点的节点上调用了
setNodeValue
方法。实际上,您的代码可能正在修改元素节点,因此没有任何结果

要进一步解释这一点,请参阅您的文档:

<mytag> this value is to be changed </mytag>
元素节点的值始终为null,因此在这些节点上设置值不会修改子文本节点的值。使用其中一个答案中建议的setTextContent将起作用,因为它会修改TextNode的值,而不是元素的值

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

if (node != null && node.getNodeType() == Node.TEXT_NODE) {
    node.setNodeValue(nodeValue);
    return true;
}
Element (name = mytag, value = null)
  - TextNode (name = #text, value= " this value is to be changed ")
if (node != null && node.getNodeType() == Node.TEXT_NODE) {
    node.setNodeValue(nodeValue);
    return true;
}