如何在一个存在的xml文档中把xml格式的string写入到该文件

解决方案 »

  1.   

    Document doc = DocumentHelper.createDocument();
    doc.addProcessingInstruction("xml-stylesheet", "type='text/xsl href='students.xsl'");
    Element root = doc.addElement("students");
    Element eltStu1 = root.addElement("student").addAttribute("sn", "01");
    Element eltName1 = eltStu1.addElement("name");
    Element eltAge1 = eltStu1.addElement("age");
    eltName1.setText("张三");
    eltAge1.setText("20");
      
    Element eltStu2 = root.addElement("student").addAttribute("sn", "02");
    Element eltName2 = eltStu2.addElement("name");
    Element eltAge2 = eltStu2.addElement("age");
    eltName2.setText("李四");
    eltAge2.setText("18");
      
    try {
    OutputFormat format = new OutputFormat(" ", true);
    format.setEncoding("gb2312");
    // 可以把System.out改为你要的流。
    XMLWriter xmlWriter = new XMLWriter(new PrintWriter(new File("MyXml.xml")), format);
    xmlWriter.write(doc);
    xmlWriter.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
      

  2.   

    有一个变通的方法:将xml读到dataset中 -> 修改dataset中的数据 -> 将dataset写入到xml数据量大,这个不可取,可以搜索一下:asp.net xml读写
      

  3.   

    XmlDocument d = new XmlDocument();
    d.LoadXml(strXml);
      

  4.   

    XmlDocument d = new XmlDocument();
    d.LoadXml(strXml);
    doc.DocumentElement.AppendChild(d.DocumentElement);之类的方法或者ImportNode方法http://msdn.microsoft.com/zh-cn/library/system.xml.xmldocument.importnode.aspxXmlDocument doc = new XmlDocument();
        doc.LoadXml("<bookstore>" +
                    "<book genre='novel' ISBN='1-861001-57-5'>" +
                    "<title>Pride And Prejudice</title>" +
                    "</book>" +
                    "</bookstore>");    //Create another XmlDocument which holds a list of books.
        XmlDocument doc2 = new XmlDocument();
        doc2.Load("books.xml");    //Import the last book node from doc2 into the original document.
        XmlNode newBook = doc.ImportNode(doc2.DocumentElement.LastChild, true);
        doc.DocumentElement.AppendChild(newBook);     Console.WriteLine("Display the modified XML...");
        doc.Save(Console.Out);