问题描述
C#/.NET应用程序编程开发中,现有一个对象object
,要求将这个对象序列化成功xml文档,有哪些方法呢?
方案一
使用命名空间System.Xml.Serialization
的XmlSerializer
类来将对象序列化成xml,如下:
public static class SerializeExtension
{
public static string Serialize<T>(this T value)
{
if (value == null)
{
return string.Empty;
}
try
{
var xmlserializer = new XmlSerializer(typeof(T));
var stringWriter = new StringWriter();
using (var writer = XmlWriter.Create(stringWriter))
{
xmlserializer.Serialize(writer, value);
return stringWriter.ToString();
}
}
catch (Exception ex)
{
throw new Exception("An error occurred", ex);
}
}
}
完整示例:
using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
namespace ConsoleApp2
{
class Program
{
public static void Main()
{
var customer = new Customer
{
Id = 1,
DisplayName ="Rector"
};
var customerXml = customer.Serialize();
Console.WriteLine(customerXml);
Console.ReadLine();
}
}
public class Customer
{
public int Id { get; set; }
public string DisplayName { get; set; }
}
public static class SerializeExtension
{
public static string Serialize<T>(this T value)
{
if (value == null)
{
return string.Empty;
}
try
{
var xmlserializer = new XmlSerializer(typeof(T));
var stringWriter = new StringWriter();
using (var writer = XmlWriter.Create(stringWriter))
{
xmlserializer.Serialize(writer, value);
return stringWriter.ToString();
}
}
catch (Exception ex)
{
throw new Exception("An error occurred", ex);
}
}
}
}
输出结果:
<?xml version="1.0" encoding="UTF-8"?>
<Customer xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Id>1</Id>
<DisplayName>Rector</DisplayName>
</Customer>
方案二
使用XmlDocument
序列化对象成xml文档,如下:
public string SerializeObject(object obj)
{
System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(obj.GetType());
using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) {
serializer.Serialize(ms, obj);
ms.Position = 0;
xmlDoc.Load(ms);
return xmlDoc.InnerXml;
}
}
版权声明:本作品系原创,版权归码友网所有,如未经许可,禁止任何形式转载,违者必究。
发表评论
登录用户才能发表评论, 请 登 录 或者 注册