【问题标题】:How can I control declared namespaces in the xml generated when I serialize an object?如何控制序列化对象时生成的 xml 中声明的命名空间?
【发布时间】:2012-01-05 17:48:50
【问题描述】:

我正在将一个对象序列化为 XML,以便它可以在两个应用程序之间传递。

在我修改我的类以在其中包含一个 List(of MyCustomType) 之前,这一切正常。 此后生成的xml因新标签而失效

xsi:type="xsd:string"

它被添加到属于我的类型的键/值对中的每个“值”。

无效部分如下所示:

<Value xsi:type="xsd:string">ACA04F47-3765-4C39-A698-C4F5B29B057F</Value>

一个xml编辑器告诉我具体的错误是:

The prefix "xsi" for attribute "xsi:type"
associated with an element type "Value" is not bound.

我可以在 xml 文件中手动克服这个错误,方法是在 xml 文档的根级别声明该命名空间,如下所示:

<MySpecialClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
....

所以我的问题是:如何让 .net 序列化程序在它生成的 xml 中包含该命名空间声明?

我用来进行序列化的代码如下所示:

Protected Function SerializedClass(obj As MySpecialClass) As String
    Try
        'serialize the current object as xml and return it as a string
        Dim serializer As New NetDataContractSerializer()
        Dim stream As New MemoryStream()
        serializer.Serialize(stream, obj)
        stream.Position = 0
        Return System.Text.ASCIIEncoding.ASCII.GetString(stream.ToArray())
    Catch ex As Exception
        Throw ex
    End Try
End Function

【问题讨论】:

  • 这里重要的是:对象本身是什么样的?在思考价值被键入为“对象。-我是对的吗?

标签: .net xml serialization


【解决方案1】:

在类级别,可以使用XmlRootAttribute 来装饰您的对象,您可以使用它来定义命名空间。

要了解更多信息,请查看MSDN Documentation for XmlRootAttribute

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-01
    • 1970-01-01
    • 2011-10-30
    • 1970-01-01
    相关资源
    最近更新 更多