序列化没有命名空间的BaseClass列表

时间:2011-07-19 18:17:15

标签: .net serialization namespaces xml-serialization

我有BaseClass List

Public Class Package

  <XmlElement("OBJECT")>
  Public List As List(Of baseobj)
  Public Sub New()
    List = New List(Of baseobj)
    Dim f As New First()
    Dim s As New Second()
    List.Add(s)
    List.Add(f)
  End Sub

  Function Serialize() As String
    Dim XmlSerializer As New XmlSerializer(GetType(Package), "")
    Dim NS As New XmlSerializerNamespaces()
    Dim SB As New StringBuilder
    Dim str As New StringWriter(SB)
    NS.Add("", "")
    XmlSerializer.Serialize(str, Me, NS)
    Return SB.ToString
  End Function
End Class

基础课程

<XmlInclude(GetType(First))>
<XmlInclude(GetType(Second))>
Public MustInherit Class baseobj
  Public Common As String
  Public Sub New()
    Common = "_Common"
  End Sub
End Class

并驾驶课程

Public Class First
  Inherits baseobj
  <XmlAttribute("term")>
  Public FirstAttr As String

  Public Sub New()
    MyBase.New()
    FirstAttr = "FirstAttr"
  End Sub
End Class

Public Class Second
  Inherits baseobj
  <XmlAttribute("term")>
  Public SecAttr As String

  Public Sub New()
    MyBase.New()
    SecAttr = "SecAttr"
  End Sub
End Class

在序列化包对象(pkg.Serialize)上有这个:

<?xml version="1.0" encoding="utf-16"?>
<Package>
  <OBJECT d2p1:type="Second" term="SecAttr" xmlns:d2p1="http://www.w3.org/2001/XMLSchema-instance">
    <Common>_Common</Common>
  </OBJECT>
  <OBJECT d2p1:type="First" term="FirstAttr" xmlns:d2p1="http://www.w3.org/2001/XMLSchema-instance">
    <Common>_Common</Common>
  </OBJECT>
</Package>

如何将包对象序列化为

<?xml version="1.0" encoding="utf-16"?>
<Package>
  <OBJECT Type="Second" term="SecAttr" >
    <Common>_Common</Common>
  </OBJECT>
  <OBJECT Type="First" term="FirstAttr">
    <Common>_Common</Common>
  </OBJECT>
</Package>

没有名称空间和前缀

1 个答案:

答案 0 :(得分:0)

你做不到。 Type属性来自何处?

d2p1:type(通常写为xsi:type)是一个众所周知的属性,用于传达元素的实际类型。如果你可以摆脱命名空间,那么它将毫无意义。