缤纷多彩的植物信息世界

  博客园 :: 首页 :: 新随笔 :: 联系 :: 订阅 :: 管理 ::
 1using System;
 2using System.Collections.Generic;
 3using System.Linq;
 4using System.Web;
 5using System.Web.UI;
 6using System.Web.UI.WebControls;
 7using System.IO;
 8using System.Xml.Serialization;
 9
10
11public partial class SimplySerialization : System.Web.UI.Page
12{
13    protected void Page_Load(object sender, EventArgs e)
14    {
15        string xmlFilePath = @"C:\Data\Category.xml";
16        Category categoryObj = new Category();
17        categoryObj.CategoryID = 1;
18        categoryObj.CategoryName = "啤酒";
19        categoryObj.Description = "软饮料,咖啡,茶,啤酒和白酒";
20
21        //重命名CategoryID为ID,并添加为属性
22        XmlAttributeAttribute categoryIDAttribute = new XmlAttributeAttribute();
23        categoryIDAttribute.AttributeName = "ID";
24        XmlAttributes attributesIdCol = new XmlAttributes();
25        attributesIdCol.XmlAttribute = categoryIDAttribute;
26        XmlAttributeOverrides attrOverrides = new XmlAttributeOverrides();
27        attrOverrides.Add(typeof(Category), "CategoryID", attributesIdCol);
28
29        //重命名CategoryName为Name,并添加到element
30        XmlElementAttribute categoryNameElement = new XmlElementAttribute();
31        categoryNameElement.ElementName = "Name";
32        XmlAttributes attributesNameCol = new XmlAttributes();
33        attributesNameCol.XmlElements.Add(categoryNameElement);
34        attrOverrides.Add(typeof(Category), "CategoryName", attributesNameCol);
35
36        XmlSerializer serializer = new XmlSerializer(typeof(Category),attrOverrides);
37        TextWriter writer = new StreamWriter(xmlFilePath);
38        serializer.Serialize(writer, categoryObj);
39        writer.Close();
40        Response.Write("文件写入成功!");
41
42    }

43}

44

 

输出XML文档的结果

1<?xml version="1.0" encoding="utf-8"?>
2<Category xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" ID="1">
3  <Name>啤酒</Name>
4  <Description>软饮料,咖啡,茶,啤酒和白酒</Description>
5</Category>

 

posted on 2009-04-16 22:52  虎克  阅读(325)  评论(0)    收藏  举报