如何使用Linq序列化为xml

时间:2012-02-29 15:47:03

标签: c# linq

如何使用Linq将大学实例序列化为XML?

class College
{
    public string Name { get; set; }
    public string Address { get; set; }
    public List<Person> Persons { get; set; }
}


class Person
{
    public string Gender { get; set; }
    public string City { get; set; }
}

6 个答案:

答案 0 :(得分:6)

您无法使用LINQ进行序列化。您可以使用XmlSerializer

  XmlSerializer serializer = new XmlSerializer(typeof(College));

  // Create a FileStream to write with.
  Stream writer = new FileStream(filename, FileMode.Create);
  // Serialize the object, and close the TextWriter
  serializer.Serialize(writer, i);
  writer.Close();

答案 1 :(得分:5)

不确定为什么人们说你不能用LINQ序列化/反序列化。自定义序列化仍然是序列化:

public static College Deserialize(XElement collegeXML)
{
    return new College()
           {
               Name = (string)collegeXML.Element("Name"),
               Address = (string)collegeXML.Element("Address"),
               Persons = (from personXML in collegeXML.Element("Persons").Elements("Person")
                          select Person.Deserialize(personXML)).ToList()
           }
}

public static XElement Serialize(College college)
{
    return new XElement("College",
               new XElement("Name", college.Name),
               new XElement("Address", college.Address)
               new XElement("Persons", (from p in college.Persons
                                        select Person.Serialize(p)).ToList()));
);

请注意,这可能不是最好的方法,但它至少会回答这个问题。

答案 2 :(得分:1)

您必须使用XML序列化

static public void SerializeToXML(College college)
{
  XmlSerializer serializer = new XmlSerializer(typeof(college));
  TextWriter textWriter = new StreamWriter(@"C:\college.xml");
  serializer.Serialize(textWriter, college);
  textWriter.Close();
}

答案 3 :(得分:1)

你不能使用LINQ。请查看以下代码作为示例。

// This is the test class we want to 
// serialize:
[Serializable()]
public class TestClass
{
    private string someString;
    public string SomeString
    {
        get { return someString; }
        set { someString = value; }
    }

    private List<string> settings = new List<string>();
    public List<string> Settings
    {
        get { return settings; }
        set { settings = value; }
    }

    // These will be ignored
    [NonSerialized()]
    private int willBeIgnored1 = 1;
    private int willBeIgnored2 = 1;

}

// Example code

// This example requires:
// using System.Xml.Serialization;
// using System.IO;

// Create a new instance of the test class
TestClass TestObj = new TestClass();

// Set some dummy values
TestObj.SomeString = "foo";

TestObj.Settings.Add("A");
TestObj.Settings.Add("B");
TestObj.Settings.Add("C");


#region Save the object

// Create a new XmlSerializer instance with the type of the test class
XmlSerializer SerializerObj = new XmlSerializer(typeof(TestClass));

// Create a new file stream to write the serialized object to a file
TextWriter WriteFileStream = new StreamWriter(@"C:\test.xml");
SerializerObj.Serialize(WriteFileStream, TestObj);

// Cleanup
WriteFileStream.Close();

#endregion


/*
The test.xml file will look like this:

<?xml version="1.0"?>
<TestClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <SomeString>foo</SomeString>
  <Settings>
    <string>A</string>
    <string>B</string>
    <string>C</string>
  </Settings>
</TestClass>         
*/

#region Load the object

// Create a new file stream for reading the XML file
FileStream ReadFileStream = new FileStream(@"C:\test.xml", FileMode.Open, FileAccess.Read, FileShare.Read);

// Load the object saved above by using the Deserialize function
TestClass LoadedObj = (TestClass)SerializerObj.Deserialize(ReadFileStream);

// Cleanup
ReadFileStream.Close();

#endregion


// Test the new loaded object:
MessageBox.Show(LoadedObj.SomeString);

foreach (string Setting in LoadedObj.Settings)
    MessageBox.Show(Setting);

答案 4 :(得分:1)

如果序列化后需要XDocument对象,则可以使用它

DataClass dc = new DataClass();

XmlSerializer x = new XmlSerializer(typeof(DataClass));
MemoryStream ms = new MemoryStream();
x.Serialize(ms, dc);
ms.Seek(0, 0);

XDocument xDocument = XDocument.Load(ms); // Here it is!

答案 5 :(得分:0)

我不确定这是不是你想要的,而是用这个来制作XML文档:

College coll = ...
XDocument doc = new XDocument(
  new XElement("College",
    new XElement("Name", coll.Name),
    new XElement("Address", coll.Address),
    new XElement("Persons", coll.Persons.Select(p =>
      new XElement("Person",
        new XElement("Gender", p.Gender),
        new XElement("City", p.City)
      )
    )
  )
);