C# xml序列化和反序列化
2024-01-08 13:30:30
问题
有的项目使用webservice返回结果是xml,需要进行xml序列化和反序列化
xml序列化相关特性
C#中,XML序列化相关的特性主要包括:
XmlIgnore
:这个特性可以用来指示序列化过程忽略一个属性或一个字段。当使用XmlIgnore特性时,被标记的属性或字段将不会被序列化到XML。XmlAttribute
:这个特性可以用来指示序列化过程将一个属性或字段作为一个XML属性而不是元素。XmlElement
:这个特性可以用来指定序列化过程将一个属性或字段作为一个XML元素。XmlText
:这个特性可以用来指定序列化过程将一个属性或字段的值作为XML文本节点。XmlType
:这个特性可以用来指定序列化过程为类或结构体生成一个特定的XML类型名称。XmlRoot
:这个特性可以用来指定序列化过程的根元素名称和可选的命名空间。XmlAccessType
:这个特性可以用来指定属性或字段的访问类型,以控制它们在序列化过程中是否可读或可写。这些特性可以在类、属性或字段上使用,以控制C#对象如何被序列化为XML。
案例代码
XmlHelper.cs
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace XmlStu02
{
/// <summary>
/// xml帮助类
/// </summary>
public class XmlHelper
{
/// <summary>
/// 对象转化为xml字符串,如果有参数为null则不进行序列化
/// </summary>
/// <param name="obj"></param>
/// <param name="isFormat">是否进行格式化</param>
/// <param name="isNeedHeader">是否需要xml请求头</param>
/// <returns></returns>
public static string ObjectToXmlString(object obj, bool isNeedHeader = false, bool isFormat = false)
{
try
{
XmlSerializer xmlSerializer = new XmlSerializer(obj.GetType());
XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = new UTF8Encoding(false);//utf-8不带BOM //Encoding.UTF8;utf-8带BOM
if (isFormat)
{
settings.Indent = true;
settings.IndentChars = " ";
settings.NewLineChars = "\r\n";
}
if (!isNeedHeader)
{
settings.OmitXmlDeclaration = true; // 不生成声明头
}
using (var memoryStream = new MemoryStream())
using (XmlWriter xmlWriter = XmlWriter.Create(memoryStream, settings))
{
// 强制指定命名空间,覆盖默认的命名空间
XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
namespaces.Add(string.Empty, string.Empty);
xmlSerializer.Serialize(xmlWriter, obj, namespaces);
var xmlString = Encoding.UTF8.GetString(memoryStream.ToArray());
return xmlString;
};
}
catch
{
return string.Empty;
}
}
/// <summary>
/// 将XML数据反序列化为对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="xmlData"></param>
/// <returns></returns>
public static T? XmlStringToObject<T>(string xmlData) where T : class
{
// 创建XmlSerializer实例
XmlSerializer serializer = new XmlSerializer(typeof(T));
// 使用XmlReader读取XML并反序列化为Person对象
using (StringReader reader = new StringReader(xmlData))
{
XmlReader xmlReader = XmlReader.Create(reader);
T? result = serializer.Deserialize(xmlReader) as T;
return result;
}
}
}
}
FriendModel
using System.Xml.Serialization;
namespace XmlStu02
{
/// <summary>
/// 好朋友
/// </summary>
[XmlRoot("FRIEND")]
public class FriendModel
{
/// <summary>
/// 姓名
/// </summary>
[XmlAttribute("NAME")]
public string? Name { get; set; }
/// <summary>
/// 性别
/// </summary>
[XmlAttribute("SEX")]
public string? Sex { get; set; }
}
}
ChildModel
using System.Xml.Serialization;
namespace XmlStu02
{
/// <summary>
/// 孩子模型
/// </summary>
[XmlRoot("CHILD")]
public class ChildModel
{
/// <summary>
/// 姓名
/// </summary>
[XmlElement("NAME")]
public string? Name { get; set; }
/// <summary>
/// 出生日期
/// </summary>
[XmlElement("BIRTHDAY")]
public string? BirthDay { get; set; }
/// <summary>
/// 好朋友有多个
/// </summary>
[XmlElement("FRIEND")]
public List<FriendModel>? Friends { get; set; }
}
}
ParentModel
using System.Xml.Serialization;
namespace XmlStu02
{
/// <summary>
/// 父类模型
/// </summary>
[XmlRoot("PARENT")]
public class ParentModel
{
/// <summary>
/// 姓名
/// </summary>
[XmlElement("NAME")]
public string? Name { get; set; }
/// <summary>
/// 出生日期
/// </summary>
[XmlElement("BIRTHDAY")]
public string? BirthDay { get; set; }
/// <summary>
/// 孩子,有多个
/// </summary>
[XmlElement("CHILDREN")]
public List<ChildModel>? Children { get; set; }
}
}
测试
using System.Text.Json;
namespace XmlStu02
{
internal class Program
{
/// <summary>
/// 程序入口方法
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
var friend = new FriendModel();
friend.Name = "小明";
friend.Sex = "男";
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine(XmlHelper.ObjectToXmlString(friend, true, true));
var child = new ChildModel();
child.Name = "大孩子";
child.BirthDay = null;
child.Friends = new List<FriendModel>() {
friend,
new FriendModel()
{
Name="小红",
Sex="女"
}
};
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(XmlHelper.ObjectToXmlString(child, true, true));
var parnent = new ParentModel();
parnent.Name = "父亲";
parnent.BirthDay = "1970-10-01";
parnent.Children = new List<ChildModel>()
{
child,
new ChildModel()
{
Name="小孩子",
BirthDay="1995-02-18"
}
};
Console.ForegroundColor = ConsoleColor.Blue;
var parentXml = XmlHelper.ObjectToXmlString(parnent, true, true);
Console.WriteLine(parentXml);
var xmlParent = XmlHelper.XmlStringToObject<ParentModel>(parentXml);
if (xmlParent != null)
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("xml反序列化成功");
Console.ForegroundColor = ConsoleColor.Magenta;
var jsonConfig = new JsonSerializerOptions
{
WriteIndented = true, // 可选,仅用于格式化输出
Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
};
Console.WriteLine(System.Text.Json.JsonSerializer.Serialize(xmlParent, jsonConfig));
}
Console.ForegroundColor = ConsoleColor.White;
}
}
}
文章来源:https://blog.csdn.net/qq_36437991/article/details/135406256
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!