0

I have a REST service written in vb.net that returns data using the built in serializer, so if I return my data from a Class defined like this:

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

my xml will return like this:

<?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>

But how can I add a prefix to my xml elements so I could see something like:

<myLevel1:Minion>
   <mylevel2:ID>

Would I need to serialize the data myself to do this?

sbarnby71
  • 584
  • 4
  • 7
  • 21
  • You can define the namespace generated adding something like this to Minion class: ``. To control the prefix, you need to implement a serializer, this link can help you: http://stackoverflow.com/a/17798306/4730201 – Ricardo Pontual Oct 27 '16 at 10:24
  • thanks for the answer, I think it is as I first thought that I will need to serialize the data myself. It's annoying as you can set things like ElementName & NameSpace, but not the prefix. :-( – sbarnby71 Oct 27 '16 at 10:47

1 Answers1

1

Add the Namespace your Minion Class

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

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

    Public Property ID As String = ""

End Class

And add the Namespaces to the 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

Will give you this:

<?xml version="1.0"?>
<myLevel1:Minion xmlns:myLevel2="myLevel2" xmlns:myLevel1="myLevel1">
  <myLevel2:Name>minion1</myLevel2:Name>
  <myLevel1:ID>1</myLevel1:ID>
</myLevel1:Minion>
David Sdot
  • 2,343
  • 1
  • 20
  • 26