我一直在關注如何使 xmlserializer 只序列化純 xml?試圖僅序列化純文本,但是我在 VB.net 端執行此操作時遇到了一些問題
目的是防止線條<?xml version="1.0" encoding="utf-16"?>和屬性xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"顯示
我有一個子如下:
Private Sub writeXMLContent()
For Each dataItem As dataClass In dataSet
Dim emptyNameSpace As XmlSerializerNamespaces = New XmlSerializerNamespaces({XmlQualifiedName.Empty})
Dim serializer As New XmlSerializer(GetType(dataClass))
Dim settings As New XmlWriterSettings
settings.Indent = True
settings.OmitXmlDeclaration = True
Using stream As New StringWriter
Using writer = XmlWriter.Create(stream, settings)
serializer.Serialize(writer, serializer, emptyNameSpace)
'will write each line to a file here
End Using
End Using
Next
End Sub
但是我不斷遇到同樣的兩個錯誤:
- 該行
Using writer = XmlWriter.Create(stream, settings)使用 object 型別的運算元拋出錯誤必須實作 system.iDisposable - 該行
serializer.Serialize(writer, serializer, emptyNameSpace)似乎不喜歡我的第二個引數,因為它需要一個物件?我不太確定我會在這里傳遞什么物件?
uj5u.com熱心網友回復:
在
XmlWriter沒有實作IDisposable,即,它沒有Dispose方法的使用陳述句可以呼叫。只需通過不使用 Using 陳述句來修復它。Dim writer = XmlWriter.Create(stream, settings)第二個引數必須是您要序列化的物件,即,可能
dataItem在這種情況下。serializer.Serialize(writer, dataItem)
至于洗掉命名空間和注釋,這里有一個解決方案:
Sub Test()
Dim dataItem = New DataClass With {.Id = 5, .Name = "Test"}
' Serialize.
Dim serializer As New XmlSerializer(GetType(DataClass))
Dim sb As New StringBuilder()
Using writer As New StringWriter(sb)
serializer.Serialize(writer, dataItem)
End Using
Dim xml = RemoveNamespaces(sb.ToString())
Console.WriteLine(xml)
End Sub
Private Function RemoveNamespaces(ByVal xml As String) As String
Dim doc = New XmlDocument()
doc.LoadXml(xml)
' This assumes that we have only a namespace attribute on the root element.
doc.DocumentElement.Attributes.RemoveAll()
Dim settings As New XmlWriterSettings With {.Indent = True, .OmitXmlDeclaration = True}
Dim sb As New StringBuilder()
Using stringWriter As New StringWriter(sb)
Using writer = XmlWriter.Create(stringWriter, settings)
doc.WriteTo(writer)
End Using
End Using
Return sb.ToString()
End Function
它正在使用這個測驗類
Public Class DataClass
Public Property Id As Integer
Public Property Name As String
End Class
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/394883.html
