模型到XML文件的映射-如何在源XML文件中找到反序列化对象的位置
本文关键字:文件 XML 反序列化 对象 位置 映射 模型 | 更新日期: 2023-09-27 18:18:31
这是使用c#序列化器将我的模型映射到XML文件的最佳方法。我的意思是,如果我选择一个反序列化的对象,我可以在xml文件中找到xml源文本
我为你准备了一个工作示例,你可以进一步探索它。
using System;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Serialization;
using System.Collections.Generic;
using System.IO;
namespace ConsoleApplication5
{
public class Person
{
public int Age { get; set; }
public string Name { get; set; }
public int XMLLine { get; set; }
}
public class Persons : List<Person> { }
class Program
{
static void Main(string[] args)
{
//create your objects
Person p = new Person();
p.Age = 35;
p.Name = "Arnold";
Person p2 = new Person();
p2.Age = 36;
p2.Name = "Tom";
Persons ps = new Persons();
ps.Add(p);
ps.Add(p2);
//Serialize them to XML
XmlSerializer xs = new XmlSerializer(typeof(Persons));
XDocument d = new XDocument();
using (XmlWriter xw = d.CreateWriter())
xs.Serialize(xw, ps);
//print xml
//System.Diagnostics.Debug.WriteLine(d.ToString());
// it will produce following xml. You can save it to file.
//I have saved it to variable xml for demo
string xml = @"<ArrayOfPerson>
<Person>
<Age>35</Age>
<Name>Arnold</Name>
<XMLLine>0</XMLLine>
</Person>
<Person>
<Age>36</Age>
<Name>Tom</Name>
<XMLLine>0</XMLLine>
</Person>
</ArrayOfPerson>";
XDocument xdoc = XDocument.Parse(xml, LoadOptions.SetLineInfo);
// A little trick to get xml line
xdoc.Descendants("Person").All(a => { a.SetElementValue("XMLLine", ((IXmlLineInfo)a).HasLineInfo() ? ((IXmlLineInfo)a).LineNumber : -1); return true; });
//deserialize back to object
Persons pplz = xs.Deserialize((xdoc.CreateReader())) as Persons;
pplz.All(a => { Console.WriteLine(string.Format("Name {0} ,Age{1} ,Line number of object in XML File {2}", a.Name, a.Age, a.XMLLine)); return true; });
Console.ReadLine();
}
}
}
和它会给出像
这样的结果Name Arnold,Age35, XML文件2中对象行号
Name Tom,Age36, XML文件7中对象行号
你可以试试这个扩展方法:
public static string ToXml<T>(this object obj)
{
using (var memoryStream = new MemoryStream())
{
using (TextWriter streamWriter = new StreamWriter(memoryStream))
{
var xmlSerializer = new XmlSerializer(typeof(T));
xmlSerializer.Serialize(streamWriter, obj);
return Encoding.ASCII.GetString(memoryStream.ToArray());
}
}
}
public static void ToXmlFile<T>(this object obj, string fileName)
{
using (TextWriter streamWriter = new StreamWriter(fileName))
{
var xmlSerializer = new XmlSerializer(typeof(T));
xmlSerializer.Serialize(streamWriter, obj);
}
}
用法:
// you will get this on a string variable
var xmlString = yourModel.ToXml<YourModel>();
// you will save our object in a file.
yourModel.ToXmlFile<YourModel>(@"C:'yourModelDump.xml");
请注意在你的类中添加SerializableAttribute
[Serializable]
public class YourModel
{
//...
}
应该可以了