2017-10-06 67 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()); 我将节点转换为元素,然后通过标记名称 –