虎克的博客

Enthusiasm Biogeography-Biodiversity Informatics-Data Sciences

创建XML文档

| Comments

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using System.IO;

public partial class CreateXML : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        string xmlFilePath = Request.PhysicalApplicationPath + @"\App_Data\NewBooks.xml";
        XmlDocument doc = new XmlDocument();
        if (File.Exists(xmlFilePath))
        {
            doc.Load(xmlFilePath);
            XmlNode bookNode = CreateBookNode(doc);
            XmlNode bookStoreNode = doc.SelectSingleNode("bookstore");
            bookStoreNode.AppendChild(bookNode);
            lblResult.Text = "文件写入成功!";
        }
        else
        {
            XmlNode declarationNode = doc.CreateXmlDeclaration("1.0", "", "");
            doc.AppendChild(declarationNode);
            XmlComment comment = doc.CreateComment("这是一个测试性XML文档");
            doc.AppendChild(comment);

            XmlNode bookStoreNode = doc.CreateElement("bookstore");
            XmlNode bookNode = CreateBookNode(doc);

            bookStoreNode.AppendChild(bookNode);
            doc.AppendChild(bookStoreNode);

            lblResult.Text = "文件成功写入!";
        }
        doc.Save(xmlFilePath);
    }
    XmlNode CreateBookNode(XmlDocument doc)
    {
       
        XmlNode bookNode = doc.CreateElement("book");
        XmlAttribute genreAttribute = doc.CreateAttribute("genre");
        genreAttribute.Value = txtGenre.Text;
        bookNode.Attributes.Append(genreAttribute);

        XmlNode titleNode = doc.CreateElement("title");
        titleNode.InnerText = txtTitle.Text;
        bookNode.AppendChild(titleNode);

        XmlNode authorNode = doc.CreateElement("author");
        XmlNode firstNameNode = doc.CreateElement("first-name");
        firstNameNode.InnerText = txtFirstName.Text;
        authorNode.AppendChild(firstNameNode);

        XmlNode lastNameNode = doc.CreateElement("last-name");
        lastNameNode.InnerText = txtLastName.Text;
        authorNode.AppendChild(lastNameNode);

        bookNode.AppendChild(authorNode);

        XmlNode priceNode = doc.CreateElement("price");
        priceNode.InnerText = txtPrice.Text;
        bookNode.AppendChild(priceNode);

        return bookNode;
    }
    XmlNode CreateBookNodeFragment(XmlDocument doc)
    {
        XmlDocumentFragment docFragment = doc.CreateDocumentFragment();
        docFragment.InnerXml = "<book genre='" + txtGenre.Text + "'>" + "<title>" + txtTitle.Text + "</title>" + "<author><first-name>" + txtFirstName.Text + "</first-name>" + "<last-name>" + txtLastName.Text + "</last-name></author>" + "<price>" + txtPrice.Text + "</price></book>";
        return docFragment;

    }
}

Comments