模型到XML文件映射 - 如何在soucre XML文件中查找反序列化对象的位置。

时间:2011-12-22 11:51:50

标签: c# xml mapping

使用c#serializer将模型映射到XML文件的最佳方法是哪种。我的意思是,如果我选择一个反序列化的对象,我可以在XML文件中找到xml源文本。

2 个答案:

答案 0 :(得分:3)

我为你准备了一份工作样本,你可以进一步探索它。

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();

    }
  }
}

,它会给你的结果如

  

名称Arnold,Age35,XML文件2中对象的行号

     

将名称Tom,Age36,XML文件7中的对象行号

命名

答案 1 :(得分:0)

您可以尝试以下扩展方法:

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
{
  //...
}

这应该这样做