在C#中将对象序列化为xml

时间:2012-06-18 18:58:30

标签: c# xmlserializer

我在名称空间学校下面有一个简单的班级学生。

namespace XmlTestApp
{
    public class Student
    {
        private string studentId;

        public string FirstName;
        public string MI;
        public string LastName;

        public Student()
        {
            //Just provided for making Serialization work as obj.GetType() needs parameterless constructor.
        }

        public Student(String studentId)
        {
            this.studentId = studentId;
        }

    }
}

现在当我序列化这个时,我把它作为序列化的xml:

<?xml version="1.0" encoding="utf-8"?>
<Student xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <FirstName>Cad</FirstName>
  <MI>Dsart</MI>
  <LastName>dss</LastName>
</Student>

但我想要的是,基本上我需要在xml中以类名称为前缀的命名空间,这可能吗?

<?xml version="1.0" encoding="utf-8"?>
<XmlTestApp:Student xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <FirstName>Cad</FirstName>
  <MI>Dsart</MI>
  <LastName>dss</LastName>
</Student>

这是我的序列化代码:

Student s = new Student("2");
            s.FirstName = "Cad";
            s.LastName = "dss";
            s.MI = "Dsart";

            System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(s.GetType());

            TextWriter txtW=new StreamWriter(Server.MapPath("~/XMLFile1.xml"));
            x.Serialize(txtW,s);

3 个答案:

答案 0 :(得分:2)

编辑:简短回答仍然是肯定的。正确的属性实际上是XmlType属性。此外,您需要指定一个名称空间,然后在序列化代码中,您需要为将用于限定元素的名称空间指定别名。

namespace XmlTestApp
{
    [XmlRoot(Namespace="xmltestapp", TypeName="Student")]
    public class Student
    {
        private string studentId;

        public string FirstName;
        public string MI;
        public string LastName;

        public Student()
        {
            //Just provided for making Serialization work as obj.GetType() needs parameterless constructor.
        }

        public Student(String studentId)
        {
            this.studentId = studentId;
        }

    }
}

...

        Student s = new Student("2");
        s.FirstName = "Cad";
        s.LastName = "dss";
        s.MI = "Dsart";

        System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(s.GetType());

        System.Xml.Serialization.XmlSerializationNamespaces ns = new System.Xml.Serialization.XmlSerializationNamespaces();

        ns.Add("XmlTestApp", "xmltestapp");

        TextWriter txtW=new StreamWriter(Server.MapPath("~/XMLFile1.xml"));
        x.Serialize(txtW,s, ns); //add the namespace provider to the Serialize method

您可能需要设置命名空间以确保它仍然使用W3.org的XSD / XSI,但这可以让您走上正确的轨道。

答案 1 :(得分:0)

如何实现它的另一种方法是编写xml - 而不是使用visual studio中的工具 - xml到xsd。如果您有xsd,则可以使用xsdToCode

生成可序列化的类

答案 2 :(得分:0)

一个优雅的解决方案是使用XmlSerializerNamespaces来声明你的命名空间,然后将其传递给XmlSerializer

请参阅XML Serialization and namespace prefixes