2012-09-23 64 views
0

我想將XmlTextWriter輸出數據導出(轉換)爲字符串變量。使用vb.net將XmlTextWriter輸出導出爲字符串

我的代碼如下:

 '' write data as xml 
     Dim objX As New XmlTextWriter(Response.OutputStream, Encoding.UTF8) 
     objX.WriteStartDocument() 
     objX.WriteStartElement("Transaction") 
     objX.WriteAttributeString("version", "1.0") 
     objX.WriteElementString("id", "12") 
     objX.WriteElementString("token", "4534gfdgdfhfst") 


     objX.WriteEndElement() 

     objX.WriteEndDocument() 

     objX.Flush() 

     objX.Close() 
     Response.End() 

XML輸出現在我得到的是這樣的:38824e4760a1b72f9bd95723a3bdffbd02280010.50en3475990rapids1 month rapidshare0.46587748175.136.184.1539/14/2012d7a1ff2200f9fe7b8b89d12fdc8be8f36293‌​712eS. how to make it as xml tags

+0

順便說一句,你不應該使用'XmlTextWriter',不是因爲.NET 2.0。像Darin的例子一樣使用'XmlWriter.Create'。 –

+0

現在得到的xml輸出是這樣的:?38824e4760a1b72f9bd95723a3bdffbd02280010.50en3475990rapids1 month rapidshare0.46587748175.136.184.1539/14/2012d7a1ff2200f9fe7b8b89d12fdc8be8f36293712eS。如何使它作爲XML標籤 – Dan

回答

3

你有XmlTextWriter配置爲直接寫入Response.OutputStream。如果你想將它導出到一個字符串變量,你可以使用StringWriter來寫入StringBuilder

Dim sb As New StringBuilder() 
Using sw As New StringWriter(sb) 
    Using writer = XmlWriter.Create(sw) 
     ' write the XML to the writer here 
    End Using 
End Using 
' At this stage the StringBuilder will contain the generated XML. 

,你可以寫一個MemoryStream一種替代方案:

Using stream As New MemoryStream() 
    Using writer = XmlWriter.Create(stream) 
     ' write the XML to the writer here 

     Dim xml As String = Encoding.UTF8.GetString(stream.ToArray()) 
     ' TODO: do something with the generated XML 
    End Using 
End Using 
+0

你能寫完整的代碼,我試圖用StringWriter導出,但失敗。 – Dan

+0

我已更新我的答案以提供示例。 –

+0

我已經嘗試了第一個代碼,並且無法獲取XML格式,而是我只有沒有標籤的數據。 – Dan