我使用dom写入一条用户名和密码的信息到xml文件中但是只能即时读取不能保存在xml文件中,说不清楚,帮看看怎么能让数据留在xml中啊,首先是我的xml文件内容,很简单jack和lucy两个用户
<?xml version="1.0" encoding="UTF-8"?>
<users>
<user>
<username>jack</username>
<password>123</password>
</user>
<user>
<username>lucy</username>
<password>123</password>
</user>
</users>下面是java代码,先正常的解析出用户信息,然后添加一条信息再输出显示出三条用户,但是并没有保存在xml文档里。
public class dom_add_xmlInfo {
   public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException{      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();      DocumentBuilder db = dbf.newDocumentBuilder();      Document doc = db.parse(new File("d:/UserInfo.xml"));      NodeList users = doc.getElementsByTagName("user");      System.out.println("修改前");
      
      for(int i = 0;i < users.getLength();i++){
          Element user = (Element)users.item(i);
 String username = user.getElementsByTagName("username").item(0).getFirstChild().getNodeValue();
 String password = user.getElementsByTagName("password").item(0).getFirstChild().getNodeValue();
 System.out.println(username + password);
      }      Element newUser = doc.createElement("user");      Element newUserName = doc.createElement("username");      Element newPassword = doc.createElement("password");

      Text nameText = doc.createTextNode("tom");      Text pwdText = doc.createTextNode("123");

      Node nodeUserName = newUser.appendChild(newUserName).appendChild(nameText);      Node nodePassword = newUser.appendChild(newPassword).appendChild(pwdText);      Element root = doc.getDocumentElement();      Node nodeUser = root.appendChild(newUser);

      System.out.println("修改后");      for(int i = 0;i < users.getLength();i++){
          Element user = (Element)users.item(i);
 String username = user.getElementsByTagName("username").item(0).getFirstChild().getNodeValue();
 String password = user.getElementsByTagName("password").item(0).getFirstChild().getNodeValue();
 System.out.println(username + password);
      }
   }
}
输出结果:修改前
jack123
lucy123
修改后
jack123
lucy123
tom123我以为添加成功了,可下次再运行程序还是这个结果,开始我以为可能数据重复给替换了,我把tom换成lily再运行tom没了运行输出jack、lucy和lily。我发现这么写只是即时性的增加数据,于是我打开xml文档发现并没保存我添加的数据。比如我要实现一个注册的功能想把用户永久加入到xml文件中,这个问题该怎么解决呢,学的比较浅只局限于用dom操作。帮帮忙啊,谢啦  或者直接Q我361869981

解决方案 »

  1.   

    public class dom_add_xmlInfo 
    {
        public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException
        {        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        
            DocumentBuilder db = dbf.newDocumentBuilder();
            
            File userInfo = new File("d:/UserInfo.xml");
        
            Document doc = db.parse(userInfo);
        
            NodeList users = ((org.w3c.dom.Document) doc).getElementsByTagName("user");
        
            System.out.println("修改前");
             
            for(int i = 0;i < users.getLength();i++)
            {
                Element user = (Element)users.item(i);
                String username = user.getElementsByTagName("username").item(0).getFirstChild().getNodeValue();
                String password = user.getElementsByTagName("password").item(0).getFirstChild().getNodeValue();
                System.out.println(username + password);
            }
        
            Element newUser = doc.createElement("user");
        
            Element newUserName = doc.createElement("username");
        
            Element newPassword = doc.createElement("password");
        
            org.w3c.dom.Text nameText = doc.createTextNode("tom");
        
            org.w3c.dom.Text pwdText = doc.createTextNode("123");
        
            newUser.appendChild(newUserName).appendChild(nameText);
        
            newUser.appendChild(newPassword).appendChild(pwdText);
        
            Element root = doc.getDocumentElement();
        
            Node nodeUser = root.appendChild(newUser);
            
            //写入文件
            FileWriter file = new FileWriter(userInfo);
            file.write(nodeUser.getTextContent());
            file.flush();
            file.close();
        
            System.out.println("修改后");
        
            for(int i = 0;i < users.getLength();i++)
            {
                Element user = (Element)users.item(i);
                String username = user.getElementsByTagName("username").item(0).getFirstChild().getNodeValue();
                String password = user.getElementsByTagName("password").item(0).getFirstChild().getNodeValue();
                System.out.println(username + password);
            }
        }
    }
      

  2.   

    每次添加完后记得把修改过后的内容写到xml文件中
      

  3.   

    public class WriteNode2XML
    {    private FileWriter out;
        
        private boolean flag = false;    public WriteNode2XML(FileWriter out)
        {
            this.out = out;
        }    public void close() throws IOException
        {
            out.close();
        }    public void flush() throws IOException
        {
            out.flush();
        }    public void write(Node node) throws IOException
        {
            write(node, "\n");
        }    public void write(Node node, String indent) throws IOException
        {
            switch (node.getNodeType())
            {
            case Node.DOCUMENT_NODE:
            {
                Document doc = (Document) node;
                out.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?> ");
                Node child = doc.getFirstChild();
                while (child != null)
                {
                    write(child, indent);
                    child = child.getNextSibling();
                }
                break;
            }        case Node.DOCUMENT_TYPE_NODE:
            {
                DocumentType doctype = (DocumentType) node;            out.write("!DOCTYPE " + doctype.getName() + "> ");
                break;
            }
            
            case Node.ELEMENT_NODE:
            {
                Element elt = (Element) node;
                out.write(indent + " <" + elt.getTagName());
                NamedNodeMap attrs = elt.getAttributes();
                for (int i = 0; i < attrs.getLength(); i++)
                {
                    Node a = attrs.item(i);
                    out.write("" + a.getNodeName() + "='"
                            + fixup(a.getNodeValue()) + "'");            }
                out.write(">");
                Node child = elt.getFirstChild();
                while (child != null)
                {
                    write(child, indent);
                    child = child.getNextSibling();
                }
                out.write( (flag ? indent : "") + "</" + elt.getTagName() + "> ");
                flag = true;
                break;
            }
            case Node.TEXT_NODE:
            {
                flag = false;
                Text textNode = (Text) node;
                String text = textNode.getData().trim();
                
                if ((text != null) && text.length() > 0)
                {
                    out.write(fixup(text));
                }
                break;
            }
            case Node.PROCESSING_INSTRUCTION_NODE:
            {
                ProcessingInstruction pi = (ProcessingInstruction) node;
                out.write(indent + " <? " + pi.getTarget() + "   " + pi.getData()
                        + "?> ");
                break;
            }
            case Node.CDATA_SECTION_NODE:
            {
                CDATASection cdata = (CDATASection) node;
                out.write(indent + " <" + "![CDATA[ " + cdata.getData() + "]] "
                        + "> ");
                break;
            }
            case Node.COMMENT_NODE:
            {
                Comment c = (Comment) node;
                out.write(indent + " <!--" + c.getData() + "--> ");
                break;
            }
            default:
                System.out.println("Ignoring   node:   "
                        + node.getClass().getName());
                break;
            }    }    String fixup(String s)
        {
            StringBuffer sb = new StringBuffer();
            int len = s.length();
            for (int i = 0; i < len; i++)
            {
                char c = s.charAt(i);
                switch (c)
                {
                default:
                    sb.append(c);
                    break;
                case '<':
                    sb.append("&lt; ");
                    break;
                case '>':
                    sb.append("&gt; ");
                    break;
                case '&':
                    sb.append("&amp; ");
                    break;
                case '"':
                    sb.append("&quot; ");
                    break;
                case '\'':
                    sb.append("&apos; ");
                    break;            }        }
            return sb.toString();
        }
    }
      

  4.   

    public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException
        {        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        
            DocumentBuilder db = dbf.newDocumentBuilder();
            
            File userInfo = new File("d:/UserInfo.xml");
        
            Document doc = db.parse(userInfo);
        
            NodeList users = doc.getElementsByTagName("user");
        
            System.out.println("修改前");
             
            for(int i = 0;i < users.getLength();i++)
            {
                Element user = (Element)users.item(i);
                String username = user.getElementsByTagName("username").item(0).getFirstChild().getNodeValue();
                String password = user.getElementsByTagName("password").item(0).getFirstChild().getNodeValue();
                System.out.println(username + password);
            }
        
            Element newUser = doc.createElement("user");
        
            Element newUserName = doc.createElement("username");
        
            Element newPassword = doc.createElement("password");
        
            Text nameText = doc.createTextNode("tom");
        
            Text pwdText = doc.createTextNode("123");
        
            newUser.appendChild(newUserName).appendChild(nameText);
        
            newUser.appendChild(newPassword).appendChild(pwdText);
        
            Element root = doc.getDocumentElement();
        
            root.appendChild(newUser);
            
            //写入文件
            FileWriter file = new FileWriter(userInfo);
            WriteNode2XML t = new WriteNode2XML(file);
            t.write(doc);
            t.flush();
            t.close();
        
            System.out.println("修改后");
        
            for(int i = 0;i < users.getLength();i++)
            {
                Element user = (Element)users.item(i);
                String username = user.getElementsByTagName("username").item(0).getFirstChild().getNodeValue();
                String password = user.getElementsByTagName("password").item(0).getFirstChild().getNodeValue();
                System.out.println(username + password);
            }
        }
      

  5.   


            DOMSource source = new DOMSource(doc);  
            TransformerFactory tf = TransformerFactory.newInstance();  
            Transformer t = tf.newTransformer();  
            StreamResult result = new StreamResult(new File("output.xml"));  
            t.transform(source,result);  
    http://blog.csdn.net/xiazdong/article/details/6841759