Skip to main content
 首页 » 编程设计

c#之自定义 xsd.exe 工具和区分大小写的 xml 序列化

2024年02月20日20jirigala

我有以下 xsd:

<?xml version="1.0" encoding="UTF-8"?> 
<xsd:schema 
        targetNamespace="http://www.something.com/GetWrapRequest" 
        elementFormDefault="qualified" attributeFormDefault="qualified" version="1.0" 
        xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
        xmlns:gwreq="http://www.something.com/GetWrapRequest"> 
 
    <xsd:element name="message" type="gwreq:Message"> 
        <xsd:annotation> 
            <xsd:documentation>Complete message</xsd:documentation> 
        </xsd:annotation> 
    </xsd:element> 
    <xsd:complexType name="Message"> 
        <!-- something here --> 
    </xsd:complexType> 
</xsd:schema> 

为了生成 C# 类,我使用了来自 http://hosca.com/blog/post/2008/12/26/Generating-C-classes-from-FpML-Schema.aspx 的修改代码我不能使用通常的 xsd.exe,因为我需要从 XML 命名空间创建 C# 命名空间,而 xsd.exe 将所有类放置到一个 C# 命名空间。所以我找到了这段代码并将其扩展以创建正确的 namespace 。但是与将 xsd 转换为 CodeDom 相关的所有部分仍然相同。

我现在的问题是 xsd.exe 正在生成这个:

[System.Xml.Serialization.XmlRootAttribute("message", Namespace="http://www.something.com/GetWrapRequest", IsNullable=true)] 
public partial class Message {} 

我的代码生成了这个:

[System.Xml.Serialization.XmlRootAttribute(Namespace="http://www.something.com/GetWrapRequest", IsNullable=true)] 
public partial class Message {} 

如您所见,属性中缺少带有小写“m”的“消息”。并且因为我需要反序列化的 xml 也带有带有较低“m”的标签“消息”反序列化失败。

我该如何解决这个问题?我查看了 XmlSchemaImporter 和 XmlCodeExporter 的选项,但没有什么能解决问题。或者我能否以某种方式设置 XmlSerializer 以禁用区分大小写?

请您参考如下方法:

所以在潜入 Xsd2Code 源代码后,我发现了一件有趣的事情。我正在使用这两个循环来创建 xml 映射

foreach (XmlSchemaType schemaType in rootSchema.SchemaTypes.Values) 
    xmlTypeMappings.Add(xmlSchemaImporter.ImportSchemaType(schemaType.QualifiedName)); 
foreach (XmlSchemaElement schemaElement in rootSchema.Elements.Values) 
    xmlTypeMappings.Add(xmlSchemaImporter.ImportTypeMapping(schemaElement.QualifiedName)); 

但在 Xsd2Code 中,它们首先处理元素,然后处理模式类型。所以我只是将它们的顺序更改为这样的循环:

foreach (XmlSchemaElement schemaElement in rootSchema.Elements.Values) 
    xmlTypeMappings.Add(xmlSchemaImporter.ImportTypeMapping(schemaElement.QualifiedName)) 
foreach (XmlSchemaType schemaType in rootSchema.SchemaTypes.Values) 
    xmlTypeMappings.Add(xmlSchemaImporter.ImportSchemaType(schemaType.QualifiedName)); 

并生成元素名为“message”的正确 XmlRootAttribute。