gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 11:20:42 26 4
gpt4 key购买 nike

我在命名空间 School 下有一个简单的类 Student。

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

最佳答案

编辑:简短的回答仍然是肯定的。正确的属性实际上是 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,但这应该能让您走上正轨。

关于c# - 在 C# 中将对象序列化为 xml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11089275/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com