2

我在命名空间学校下有一个简单的学生类。

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

3 回答 3

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,但这应该会让您走上正轨。

于 2012-06-18T19:03:59.937 回答
0

如何实现它的另一种方法是编写你的 xml - 而不是使用 Visual Studio 中的工具 - xml 到 xsd。如果你有 xsd,你可以用 xsdToCode 生成可序列化的类

于 2012-06-18T19:04:23.387 回答
0

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

请参阅XML 序列化和命名空间前缀

于 2012-06-18T19:08:44.007 回答