c# - 在 xsd.exe 生成的类之后设置适当的 XML 命名空间

标签 c# xml serialization xsd

我使用 xsd.exe 工具从 xsd 生成了 c# 类。在原始架构中,命名空间如下:

<xs:schema xmlns="http://TheXsdGivenSchema.com/SOMETHING/1.0/stuff" xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://TheXsdGivenSchema.com/SOMETHING/1.0/stuff" elementFormDefault="qualified" attributeFormDefault="unqualified">

生成的类中的根如下:

[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]    
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://TheXsdGivenSchema.com/SOMETHING/1.0/stuff")]    
[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://TheXsdGivenSchema.com/SOMETHING/1.0/stuff", IsNullable = false)]          

我的问题是,在我序列化这个类之后,我得到了一个具有以下架构的 XML:

<someThing xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://TheXsdGivenSchema.com/SOMETHING/1.0/stuff">

但我需要的是:

<tns:someThing xmlns:tns="http://TheXsdGivenSchema.com/SOMETHING/1.0/stuff" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://TheXsdGivenSchema.com/SOMETHING/1.0/stuff">

为了让事情变得更有趣,我需要在根节点和一些其他节点中添加 tns: 前缀。像这样:

<tns:someThing xmlns:tns="http://TheXsdGivenSchema.com/SOMETHING/1.0/stuff" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://TheXsdGivenSchema.com/SOMETHING/1.0/stuff">
<tns:header>
    <tns:request>id-707</tns:request>
    <tns:timestamp>2015-01-29T12:18:29+01:00</tns:timestamp>
</tns:header>
<tns:user>
    <tns:user>myUserName</tns:user> 
    <tns:password>hashedPwd</tns:password>
</tns:user>
<someOperations>
    <someOperation>
         <id>1212</id>
         <name>nameOfThis</name>
    </someOperation>
</someOperations>
</tns:someThing>

如何正确设置这些命名空间和前缀?提前致谢!

最佳答案

这种方法应该有助于命名空间前缀:

var namespaces = new XmlSerializerNamespaces();
namespaces.Add("tns", "http://TheXsdGivenSchema.com/SOMETHING/1.0/stuff");
var serializer = new XmlSerializer(typeof(entity));
serializer.Serialize( stream, entity, namespaces);

取自这个答案:https://social.msdn.microsoft.com/Forums/vstudio/en-US/2ed55114-0f1b-4e54-b597-21fe1a61f06b/add-prefixes-and-namesapce-to-xml-serialization?forum=csharpgeneral

关于c# - 在 xsd.exe 生成的类之后设置适当的 XML 命名空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28568507/

相关文章:

c# - 我应该使方法虚拟还是抽象?

jquery - 使用 JQuery 解析 XML

java - 将 MarkupBuilder 与 Groovy 结合使用...创建 XML 参数时出现问题

c# xml serialization 自定义 elementName

c# - 使用反射的 Wcf 动态托管

C# System.RegEx 在不应该匹配 LF 时匹配

c# - 使用自动生成的序列化程序导致数据丢失

c# - 使用 C# 将非常大的项目列表序列化到 Azure blob 存储中

c# - 使用 C# HttpClient API 和 postman 测试的区别?客户端调用适用于 postman ,但不适用于 C# httpClient getAsync

Java 从 SOAP 服务 URL 调用获取响应