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

时间:2015-02-17 18:27:06

标签: 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">

为了让事情变得更有趣,我需要在root和其他一些节点中使用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>

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

1 个答案:

答案 0 :(得分:0)

此方法应有助于命名空间前缀:

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