2017-10-06 69 views
0

我必須更改在eElement中找到的與舊值匹配的值。xml在java中使用dom更新值

我試用eElement.setAttribute(...)功能和setTextContent功能,但它不起作用。

如果我們假設新值存儲在名爲newValue的字符串變量中,我該如何讓我的代碼運行?

NodeList leaf = doc.getElementsByTagName(relativeLeaf); 
System.out.println(leaf.item(0).getNodeName()); 
for (int temp = 0; temp < leaf.getLength(); temp++) { 
    Node nNode = leaf.item(temp); 
    if (nNode.getNodeType() == Node.ELEMENT_NODE) { 
     Element eElement = (Element) nNode; 
     String oldValueInCells = eElement.getElementsByTagName(relativeLeaf).item(0).getTextContent(); 
     System.out.println("old tag : " + eElement.getElementsByTagName(relativeLeaf).item(0).getTextContent()); 
     if(oldValueInCells.contentEquals(oldVal)){ 
      // #### 
      // here i have to change tha value in eElement 
      // where it match with the old Value with a new one  
     } 
    } 
} 

回答

0

基於文檔,我認爲你可以得到節點元素,然後設置一個值。你首先應該得到的節點元素是這樣的:

Node node = eElement.getElementsByTagName(relativeLeaf).item(0); //You get the node here so you can use it as well to create OldValueInCells 
String oldValueInCells = node.getTextContent(); 
     System.out.println("old tag : " + oldValueInCells); 
     if(oldValueInCells.contentEquals(oldVal)){ 
      // #### 
      // here i have to change tha value in eElement 
      // where it match with the old Value with a new one  
      node.setTextContent("new value"); //Here you will set the value to the node 
     } 

來源:https://docs.oracle.com/javase/7/docs/api/org/w3c/dom/Node.html

+0

謝謝您的回答=),我嘗試,但該方法不更新值。我粘貼測試代碼。 \t \t \t \t \t如果(eElement.getElementsByTagName( 「描述」)。項(0).getTextContent()。contentEquals( 「X」)){ \t \t \t \t \t \t \t \t \t \t \t \t nNode。 setNodeValue( 「CO」); \t \t \t \t \t \t的System.out.println( 「描述:」 +((元件)nNode).getElementsByTagName( 「描述」)項目(0).getTextContent()); \t \t \t \t \t} 等功能運作良好,但它不明白,必須改變的價值。可能是什麼問題? –

+0

如果價值已更新,您感覺如何? –

+0

((Element)nNode).getElementsByTagName(「description」)。item(0).getTextCo ntent()); 我將節點轉換爲元素,然後通過標記名稱 –