2011-06-10 84 views
0

我有一個文檔org.w3c.dom.Document,我想要替換xml中特定標記的值。我嘗試過但以某種方式它沒有工作。它沒有給出錯誤,但是我無法看到價值的變化。更改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> 

我想要的標籤值被chnaged到nodeValue.My代碼亙古不給任何錯誤,但我看不到的變化值。

回答

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;是你正在尋找。

4

嘗試node.setTextContent(nodeValue)而不是node.setNodeValue(nodeValue)

0

查看此代碼...可以幫助您。

<folks> 
<person> 
    <name>Sam Spade</name> 
    <email>[email protected]</email> 
</person> 
<person> 
    <name>Sam Diamond</name> 
    <email>[email protected]</email> 
</person> 
<person> 
    <name>Sam Sonite</name> 
    <email>[email protected]</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); 
    } 
} 
} 
2

一個節點上使用setNodeValue改變它的價值會的工作,但只有當它是一個文本節點。極有可能,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; 
}