日期:2014-05-18  浏览次数:20781 次

如何修改DOM树中的一个结点值
list.xml:
<?xml version="1.0" encoding="utf-8"?>
<markbook>
  <notes>
  <Fir>151</Fir>
  <Sec>130</Sec>
  <Thr>76</Thr>
  <Fou>25</Fou>
  </notes>
</markbook>
现有一个结点为:Fir,我想修改它的值,用了以下代码://fir我从外读取的String类数据
note.getElementsByTagName("Fir").item(0).getFirstChild().setNodeValue(fir);
其中:这个程序我是用JAVA写的,note是这样得到的:
  DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
DocumentBuilder builder=factory.newDocumentBuilder();
doc=builder.parse("list.xml");
doc.normalize();
NodeList notes=doc.getElementsByTagName("notes");
note=(Element)notes.item(0);
对于这些结点我可以读取数据值,但是修改它们的值却不行,从不改不了,还请高手帮忙~~

------解决方案--------------------
用setTextContent, 不是setNodeValue
------解决方案--------------------
Java code

package com.aowin.sms.util;

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.xml.sax.SAXException;

public class XmlFile {
    private DocumentBuilderFactory dbf = null;

    private DocumentBuilder db = null;

    private Document d = null;
    
    private File file = null;

    public XmlFile(String fileName) {
        this(new File(fileName));
    }
    
    public XmlFile(File file) {
        try {
            dbf = DocumentBuilderFactory.newInstance();
            db = dbf.newDocumentBuilder();
            this.file = file;
        } catch (ParserConfigurationException e) {
            System.out.println(e.getMessage());
        } 
    }

    public void createRootElement(String name) {
        d = db.newDocument();
        Element root = d.createElement(name);
        d.appendChild(root);
        write();
    }

    public void appendElement(String tagname, String name) {
        appendElement(tagname, name, 0);
    }

    public void appendElement(String tagname, String name,  int index){
        try {
            d = db.parse(file);
            Element child = d.createElement(name);
            NodeList fe = d.getElementsByTagName(tagname);
            Node father = fe.item(index);
            father.appendChild(child);
            write();
        } catch (SAXException e) {
            System.out.println(e.getMessage());
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }
    
    public void appendElement(String tagname, String name, String value, int index){
        try {
            d = db.parse(file);
            NodeList fe =