0

我认为这将是一件容易的事,但我似乎迷失在了兔子洞里。

我正在尝试将一个类转换为 XML,然后是一个字节数组,以便将其作为 WCF Restful Web 服务的 HTTPWebRequest 的内容发送。我的代码会将类作为字节数组中的 XML 返回,但格式不正确。XML 如下所示:

<?xml version="1.0" encoding="utf-8"?><Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><FirstName>Richard</FirstName><LastName>Cranium</LastName></Person>

我试图使用 OmitXmlDeclaration 方法,认为这将消除额外的声明,但它不适用于 xmltextwriter 对象,并且当我使用 xmlwriterobject 时,我无法确定如何将结果转换为 Byte 数组。

这是我的代码:

    Private Shared Function GenerateXMLPersonAsByte(strFirstName As String, strLastName As String) As Byte()
    ' This should serialize this to a byte array

    Dim p As New Person()
    p.FirstName = strFirstName
    p.LastName = strLastName

    ' Want to use this with the xmlTextWriter but it does not support the property it is to be used with the XMLWriter instead
    'Dim settings As XmlWriterSettings = New XmlWriterSettings()
    'settings.OmitXmlDeclaration = True
    'settings.ConformanceLevel = ConformanceLevel.Fragment
    'settings.CloseOutput = False

    ' Create the XmlWriter object and write some content. 
    Dim mStream As New MemoryStream()
    Dim ser As New XmlSerializer(GetType(Person))
    Dim xmlTW As New XmlTextWriter(mStream, Encoding.UTF8)
    ser.Serialize(xmlTW, p)
    mStream = DirectCast(xmlTW.BaseStream, MemoryStream)

    mStream.Close()
    Return mStream.ToArray()

End Function

为了获得带有正确开始标记的 XML,我必须做什么?或如何将 XmlTextWriter 对象的输出获取到字节数组?

4

1 回答 1

0

我无法回答整个问题,但先转换为字符串

Dim myXmlString As String   
Dim myStringWriter As New StringWriter()
Dim myXmlTextWriter As XmlTextWriter = New XmlTextWriter(myStringWriter)
'Write XML, and then flush the writer...
myXmlTextWriter.Flush() 
'Return text from string writer...
myXmlString = myStringWriter.ToString()
'Close the Objects...
myStringWriter.Close()
myXmlTextWriter.Close()

然后使用(对不起,C#,但你得到.NET调用)转换为字节

byte[] data = ASCIIEncoding.UTF8.GetBytes(myXmlString);
于 2013-07-12T18:04:31.353 回答