【问题标题】:Set proper XML namespaces after classes generated by xsd.exe在 xsd.exe 生成的类之后设置适当的 XML 命名空间
【发布时间】:2015-02-17 18:27:06
【问题描述】:

我使用 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>

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

【问题讨论】:

  • 您想要的输出有两个相同的命名空间,xmlns:tns="http://TheXsdGivenSchema.com/SOMETHING/1.0/stuff"xmlns="http://TheXsdGivenSchema.com/SOMETHING/1.0/stuff"。这是不必要的。但是,鉴于两者之一是默认命名空间,tns: 前缀是多余的。你确定还是需要它吗?
  • 是的,客户给的xsd需要。我被这个问题困住了。
  • xsd 要求元素在指定的 namespace 中,它们就是。但是 XSD 没有指定如何在 XML 文件中实现。前缀实际上只是一个查找实际名称空间的本地查找键,它本身没有任何意义。事实上usersomeOperations 在同一个命名空间中,只是文件重复的查找键,一个元素使用一个键,而另一个元素使用另一个键。

标签: c# xml serialization xsd


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2012-11-14
    • 1970-01-01
    • 2013-03-16
    • 1970-01-01
    • 2019-02-15
    • 2017-03-14
    • 1970-01-01
    • 2012-04-01
    • 2013-11-28
    相关资源
    最近更新 更多