将xml前缀添加到vb.net中的默认序列化程序

时间:2016-10-27 09:17:30

标签: xml vb.net rest wcf

我有一个用vb.net编写的REST服务,它使用内置的序列化程序返回数据,所以如果我从这样定义的类中返回我的数据:

Public Class Minion
    Public Property Name As String = ""
    Public Property ID As String = ""
End Class

我的xml会像这样返回:

<?xml version="1.0"?>
<Minion xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/Testv3">
   <ID>1</ID>
   <Name>Kevin</Name>
</Minion>

但是如何为我的xml元素添加前缀,以便我可以看到类似的内容:

<myLevel1:Minion>
   <mylevel2:ID>

我是否需要自己序列化数据才能执行此操作?

1 个答案:

答案 0 :(得分:1)

添加您的Minion Class的命名空间

<XmlRoot([Namespace]:="myLevel1")>
Public Class Minion

    <XmlElement([Namespace]:="myLevel2")>
    Public Property Name As String = ""

    Public Property ID As String = ""

End Class

将命名空间添加到Serializer:

        Dim _xs As New XmlSerializer(GetType(Minion))

        Dim xn As New XmlSerializerNamespaces
        xn.Add("myLevel1", "myLevel1")
        xn.Add("myLevel2", "myLevel2")

        Using _fs As New FileStream("test.xml", FileMode.Create)
            _xs.Serialize(_fs, New Minion With {.ID = 1, .Name = "minion1"}, xn)    
        End Using

会给你这个:

<?xml version="1.0"?>
<myLevel1:Minion xmlns:myLevel2="myLevel2" xmlns:myLevel1="myLevel1">
  <myLevel2:Name>minion1</myLevel2:Name>
  <myLevel1:ID>1</myLevel1:ID>
</myLevel1:Minion>