Click here to Skip to main content
15,885,309 members
Please Sign up or sign in to vote.
3.12/5 (3 votes)
See more:
I would like to create the following xml document in vb.net
How do I do that?

XML
<?xml version="1.0" encoding="UTF-8"?>
<MyMessage>
   <Request>
	<User>
	  <PersonName>
	     <Name>My Username</Name>
	  </PersonName>
        </User>
   </Request>
   <CarVin>1234566</CarVin>
</MyMessage>


What I have tried:

I am not sure how to do it. Please help
Posted
Updated 26-Sep-17 23:54pm

There are many different ways depending on how your application works.

One method is to have a class, get the properties, then serialize & deserialize to/from XML.

So here is a class representation of your XML:
VB
Public Class PersonName

    Public Property Name() As String

End Class

Public Class User

    Public Property PersonName() As PersonName

End Class

Public Class Request

    Public Property User() As User

End Class

<XmlRoot(ElementName:="MyMessage")>
Public Class MyMessage

    Public Property Request() As Request

    Public Property CarVin() As String

End Class

Next we need to wrap the serialization code into a helper class. This is what we use in our commercial software (converted to VB):
VB
Imports System.Xml.Serialization
Imports System.Xml
Imports System.IO
Imports System.Text

Public NotInheritable Class XmlHelper
    Private Sub New()
    End Sub
    Public Shared Function FromClass(Of T)(data As T, _
                      Optional ns As XmlSerializerNamespaces = Nothing) As String
        Dim response As String = String.Empty

        Dim ms = New MemoryStream()
        Try
            ms = FromClassToStream(data)

            If ms IsNot Nothing Then
                ms.Position = 0
                Using sr = New StreamReader(ms)
                    response = sr.ReadToEnd()
                End Using

            End If
        Finally
            ' don't want memory leaks...
            ms.Flush()
            ms.Dispose()
            ms = Nothing
        End Try

        Return response
    End Function

    Public Shared Function FromClassToStream(Of T)(data As T, _
                      Optional ns As XmlSerializerNamespaces = Nothing) As MemoryStream
        Dim stream = Nothing

        If data IsNot Nothing Then
            Dim settings = New XmlWriterSettings() With
            {
                .Encoding = Encoding.UTF8,
                .Indent = True,
                .ConformanceLevel = ConformanceLevel.Auto,
                .CheckCharacters = True,
                .OmitXmlDeclaration = False
            }

            Try
                'XmlSerializer ser = new XmlSerializer(typeof(T));
                Dim serializer As XmlSerializer = _
                    XmlSerializerFactoryNoThrow.Create(GetType(T))

                stream = New MemoryStream()
                Using writer As XmlWriter = XmlWriter.Create(stream, settings)
                    serializer.Serialize(writer, data, ns)
                    writer.Flush()
                End Using
                stream.Position = 0
            Catch ex As Exception
                stream = Nothing
#If DEBUG Then
                Debug.WriteLine(ex)
                Debugger.Break()
#End If
            End Try
        End If

        Return stream

    End Function

    Public Shared Function ToClass(Of T)(data As String) As T

        Dim response = Nothing

        If Not String.IsNullOrEmpty(data) Then
            Dim settings = New XmlReaderSettings() With
            {
                .IgnoreWhitespace = True,
                .DtdProcessing = DtdProcessing.Ignore
            }

            Try
                Dim serializer As XmlSerializer = _
                    XmlSerializerFactoryNoThrow.Create(GetType(T))

                Using sr = New StringReader(data)
                    Using reader = XmlReader.Create(sr, settings)
                        response = _
                            DirectCast(Convert.ChangeType( _
                                serializer.Deserialize(reader), GetType(T)), T)
                    End Using
                End Using
            Catch ex As Exception
#If DEBUG Then
                Debug.WriteLine(ex)
                Debugger.Break()
#End If
            End Try
        End If
        Return response

    End Function

End Class

' ref: http://stackoverflow.com/questions/1127431/xmlserializer-giving-filenotfoundexception-at-constructor/39642834#39642834
Public NotInheritable Class XmlSerializerFactoryNoThrow
    Private Sub New()
    End Sub
    Public Shared cache As New Dictionary(Of Type, XmlSerializer)()

    Private Shared SyncRootCache As New Object()

    Public Shared Function Create(type As Type) As XmlSerializer

        Dim serializer As XmlSerializer

        SyncLock SyncRootCache
            If cache.TryGetValue(type, serializer) Then
                Return serializer
            End If
        End SyncLock

        SyncLock type
            'multiple variable of type of one type is same instance
            'constructor XmlSerializer.FromTypes does not throw the first
            '     chance exception           
            'serializer = XmlSerializerFactoryNoThrow.Create(type);
            serializer = XmlSerializer.FromTypes(New Type() {type})(0)
        End SyncLock

        SyncLock SyncRootCache
            cache(type) = serializer
        End SyncLock

        Return serializer

    End Function

End Class

Now we are ready to serialize/deserialize the class <> XML:
VB
Dim message As New MyMessage With
{
    .CarVin = "1234566",
    .Request = New Request With
    {
        .User = New User With
        {
            .PersonName = New PersonName With
            {
                .Name = "My Username"
            }
        }
    }
}

' to XML
Dim rawXmlMessage = XmlHelper.FromClass(message)
Console.WriteLine(rawXmlMessage)

' from XML
Dim newMessage = XmlHelper.ToClass(Of MyMessage)(rawXmlMessage)
 
Share this answer
 
Comments
Member 11403304 27-Sep-17 8:33am    
Thanks so much for your help. I used what you gave me as an example to get my solution working. I had to work around. Again thank you
Graeme_Grant 27-Sep-17 23:20pm    
You are most welcome. :)

The helper function is a little verbose but is pulled out of, and converted to VB, from one of my commercial applications that handles far more complex data. It should cover all of your needs now and in future.
 
Share this answer
 
if you are working with XML use these tools to format and validate XML data.

XML Formatter
XML Validator
 
Share this answer
 
Quote:
I am not sure how to do it.

It is impossible to answer your question. We can't teach you programming.

There is literally tens of ways to do it, and all depend on details you didn't gave us.
The way/method to use depend on where the data comes from, its structure, what you want to do with the data, your tastes in coding, if you use an helper library or not.
It can be as simple as:
VB
User= "My Username"
CarVin= "1234566"
Msg="<?xml version=""1.0"" encoding=""UTF-8""?><MyMessage><Request><User><PersonName><Name>"+User+"</Name></PersonName></User></Request><CarVin>"+CarVin+"</CarVin></MyMessage>"
 
Share this answer
 
v2
Comments
Graeme_Grant 27-Sep-17 18:37pm    
You may want to rethink these types of answers and maybe post them as comments instead of solutions, which they really are not...
Patrice T 27-Sep-17 18:49pm    
Well, I know I have problems giving sensible answers to such poor questions that are practically unanswerable because we have no context.
Graeme_Grant 27-Sep-17 19:23pm    
I can agree with you on other occasions, but I think that you went a bit far here.

I made a similar opening comment however followed up with one working solution... Your solution is really not a solution but instead an opinion suitable only as a comment.
Patrice T 27-Sep-17 21:24pm    
I take note for future.
Graeme_Grant 27-Sep-17 21:42pm    
Sorry if I came across a little harsh but felt on this occasion I should speak up. I expect no less from others if I do the same.
Throwing another hat in the ring

VB
Dim xdoc = New XDocument(
    New XElement("MyMessage",
        New XElement("Request",
            New XElement("User",
                New XElement("PersonName",
                    New XElement("Name","My Username")))),
        New XElement("CarVin","1234566")))
xdoc.Save(AppDomain.CurrentDomain.BaseDirectory & "\file.xml")


Not the most useful code in the world in that format, but you can use it as a base to derive something more suited to your needs.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900