【问题标题】:How to modify XML node value?如何修改 XML 节点值?
【发布时间】:2011-09-28 03:23:41
【问题描述】:

我是 Java 应用程序的新开发人员。我想修改一个 XML 文件节点值。我使用了一个xml文件进行如下修改

  <staff id="2">
       <firstname>yong</firstname>
       <lastname>mook kim</lastname>
       <nickname>mkyong</nickname>
       <salary>2000000</salary>
       <age>28</age>
   </staff>

在上面的xml中,我想将工资值更改为345375。对于这个修改,我编写了如下代码

 try{
     DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
     DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
     Document doc = docBuilder.parse(new File("/sdcard/myxml.xml"));

    //Get the staff element by tag name directly
     Node nodes = doc.getElementsByTagName("staff").item(0);
    //loop the staff child node
     NodeList list = nodes.getChildNodes();

     for (int i =0; i<list.getLength();i++){
         Node node = list.item(i);

         //get the salary element, and update the value
         if("salary".equals(node.getNodeName())){
             node.setNodeValue("345375");        
         }
     }
}
    catch (Exception e) {
        e.printStackTrace();
    }

如果我使用这种方式,价值不会改变薪水。

如何修改 XML 节点值?

【问题讨论】:

  • 对我来说似乎是正确的。您是否在终止程序之前保存了文件?它可能会被丢弃。
  • 你能说一下如何保存吗?

标签: android xml xmlnode


【解决方案1】:

首先您必须意识到node.setValue() 正在修改存储在内存中的表示。知道了这一点,那么您只需要弄清楚如何将该输出写入磁盘。有关示例,请参见 this

【讨论】:

    【解决方案2】:
    node.Text = "Enter your value here"; //This will work 
    

    【讨论】:

      猜你喜欢
      • 2017-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多