您的位置:首页 > 其它

用xmldocument创建一个Xml文件

2008-11-20 14:10 489 查看
XML 文件:
<?xml version="1.0" encoding="utf-8"?>
<CategoryList>
<Category ID="01">
<MainCategory>XML</MainCategory>
<Description>This is a list my XML articles.</Description>
<Active>true</Active>
</Category>
</CategoryList>
[/code]代码如下:
<%@ Import Namespace="System.Data" %><%@ Import Namespace="System.Xml" %><%@ Page Language="C#" Debug="true" %><script  runat="server">void Page_Load(object sender, System.EventArgs e){if(!Page.IsPostBack){XmlDocument xmlDoc = new XmlDocument();// Write down the XML declarationXmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0","utf-8",null);// Create the root elementXmlElement rootNode  = xmlDoc.CreateElement("CategoryList");xmlDoc.InsertBefore(xmlDeclaration, xmlDoc.DocumentElement);xmlDoc.AppendChild(rootNode);// Create a new <Category> element and add it to the root nodeXmlElement parentNode  = xmlDoc.CreateElement("Category");// Set attribute name and value!parentNode.SetAttribute("ID", "01");xmlDoc.DocumentElement.PrependChild(parentNode);// Create the required nodesXmlElement mainNode  = xmlDoc.CreateElement("MainCategory");XmlElement descNode  = xmlDoc.CreateElement("Description");XmlElement activeNode  = xmlDoc.CreateElement("Active");// retrieve the textXmlText categoryText= xmlDoc.CreateTextNode("XML");XmlText descText  = xmlDoc.CreateTextNode("This is a list my XML articles.");XmlText activeText  = xmlDoc.CreateTextNode("true");// append the nodes to the parentNode without the valueparentNode.AppendChild(mainNode);parentNode.AppendChild(descNode);parentNode.AppendChild(activeNode);// save the value of the fields into the nodesmainNode.AppendChild(categoryText);descNode.AppendChild(descText);activeNode.AppendChild(activeText);// Save to the XML filexmlDoc.Save( Server.MapPath("categories.xml"));Response.Write("XML file created");}}</script>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: