用xmldocument创建一个Xml文件

 
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>

代码如下:

<%@ 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 declaration
XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0","utf-8",null);
// Create the root element
XmlElement rootNode  = xmlDoc.CreateElement("CategoryList");
xmlDoc.InsertBefore(xmlDeclaration, xmlDoc.DocumentElement);
xmlDoc.AppendChild(rootNode);
// Create a new <Category> element and add it to the root node
XmlElement parentNode  = xmlDoc.CreateElement("Category");
// Set attribute name and value!
parentNode.SetAttribute("ID", "01");
xmlDoc.DocumentElement.PrependChild(parentNode);
// Create the required nodes
XmlElement mainNode  = xmlDoc.CreateElement("MainCategory");
XmlElement descNode  = xmlDoc.CreateElement("Description");
XmlElement activeNode  = xmlDoc.CreateElement("Active");
// retrieve the text
XmlText 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 value
parentNode.AppendChild(mainNode);
parentNode.AppendChild(descNode);
parentNode.AppendChild(activeNode);
// save the value of the fields into the nodes
mainNode.AppendChild(categoryText);
descNode.AppendChild(descText);
activeNode.AppendChild(activeText);
// Save to the XML file
xmlDoc.Save( Server.MapPath("categories.xml"));
Response.Write("XML file created");
}
}
</script>

转载于:https://www.cnblogs.com/bccu/archive/2008/11/20/1337630.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值