反序列化时更改 XML 的名称

本文关键字:XML 反序列化 | 更新日期: 2023-09-27 17:56:24

我有 xsd 工具生成的以下代码片段:

[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class myCourseCourseStructureModule

我想把这门课称为更有意义的东西。我需要添加什么属性才能轻松更改此属性?

反序列化时更改 XML 的名称

XmlTypeAttribute 有一个构造函数,该构造函数采用一个字符串,该字符串应该是名称:MSDN 上的 XmlTypeAttribute 构造函数。 如这篇相关文章中所述,这将更改架构中复杂类型的名称。 约翰·桑德斯建议使用

[XmlElement(Name="MyAddress", Namespace="your namespace")]

以更改 XML 中的元素名称。

XmlElementAttribute

// This is the class that will be serialized.
public class XClass
{
   /* The XML element name will be XName
   instead of the default ClassName. */
   [XmlElement(ElementName = "XName")]
   public string ClassName;
}