使用XMLAttributeOverides自定义XML输出

本文介绍了一个使用C#进行XML序列化的简单实例,包括如何通过代码将自定义对象序列化为XML文件,并展示了如何调整序列化结果的格式,如重命名属性名等。
 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
12ExpandedBlockStart.gifContractedBlock.gif{
13    protected void Page_Load(object sender, EventArgs e)
14ExpandedSubBlockStart.gifContractedSubBlock.gif    {
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>

 

转载于:https://www.cnblogs.com/apiaceae/archive/2009/04/16/1437596.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值