You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
|
|
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Xml;using System.Xml.Serialization;
namespace Shentun.Peis.PlugIns.Extensions{ public class XmlHelper { public static string SerializeToXml<T>(T obj) { XmlSerializer serializer = new XmlSerializer(typeof(T)); using (StringWriter textWriter = new StringWriter()) { serializer.Serialize(textWriter, obj); return textWriter.ToString(); } }
public static T DeserializeXml<T>(string xml) { var serializer = new XmlSerializer(typeof(T)); using var reader = new StringReader(xml); return (T)serializer.Deserialize(reader); }
public static T DeserializeXmlAddRoot<T>(string xml) { // 创建 XmlDocument 来修复 XML
var xmlDoc = new XmlDocument();
// 添加根元素
var root = xmlDoc.CreateElement("root");
// 加载原始内容到根元素中
root.InnerXml = xml; xmlDoc.AppendChild(root);
// 转换为字符串
string fixedXml = xmlDoc.OuterXml; var serializer = new XmlSerializer(typeof(T)); using var reader = new StringReader(fixedXml); return (T)serializer.Deserialize(reader); } }}
|