如何在VB.NET中创建XML文档 [英] How to create XML doc in VB.NET

查看:71
本文介绍了如何在VB.NET中创建XML文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在vb.net中创建以下xml文档

我该怎么做?



I would like to create the following xml document in vb.net
How do I do that?

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

推荐答案

根据您的应用程序的工作原理,有许多不同的方法。



一种方法是有一个类,获取属性,然后序列化&反序列化到XML或从XML反序列化。



所以这里是XML的类表示:

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



接下来我们需要将序列化代码包装到一个帮助器类中。这就是我们在商业软件中使用的(转换为VB):


Next we need to wrap the serialization code into a helper class. This is what we use in our commercial software (converted to 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



现在我们准备序列化/反序列化类<> XML:


Now we are ready to serialize/deserialize the class <> XML:

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)


XmlWriter类(System.Xml) [ ^ ]。


如果您正在使用XML,请使用这些工具来格式化和验证XML数据。



XML格式化程序

XML Validator
if you are working with XML use these tools to format and validate XML data.

XML Formatter
XML Validator


这篇关于如何在VB.NET中创建XML文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆