使用XMLStreamWriter为XML添加换行

时间:2015-03-24 18:16:42

标签: xml vb.net

我一直在处理更大的应用程序中的函数,以将数据从内存中的对象导出到XML文件。目标是在稍后的时间将数据读回内存,而不是通过查询数据库来重建它。

我已经能够使用XmlWriter生成XML文档,但我不喜欢所述文档的格式。没有新的行字符,XML只是一个连续的字符串。

除了使用常规StreamWriter在每个元素的末尾添加新行之外,我还没有能够看到让XML包含换行符的方法,&每条线的正确缩进,因此它是人类可读的。

作为一个例子我得到了这个:

<?xml version="1.0" encoding="utf-8"?><Library><Database>hasp</Database><Table><Name>FLOW_ACT_LOG$</Name><Desc /><Column><Name /><DB_Name>APPL_INFO</DB_Name><Type /><Column><Name /><DB_Name>T_STAMP</DB_Name>

什么时候得到:

<?xml version="1.0" encoding="utf-8"?>
<Library>
    <Database>hasp</Database>
        <Table>
            <Name>FLOW_ACT_LOG$</Name>
            <Desc />
                <Column>
                    <Name />
                    <DB_Name>APPL_INFO</DB_Name>
                    <Type />
                <Column>
                    <Name />
                    <DB_Name>T_STAMP</DB_Name>

作为参考,我的XML生成代码如下:

''' <summary>
''' Converts the table library to an XML file for storage and later retrieval
''' </summary>
''' <param name="Mwin">The MainWin instance, which holds the DataStore with
''' the library</param>
''' <remarks></remarks>
Public Sub SaveLibrary(ByVal Mwin As MainWin)
    '
    Dim lw As System.Xml.XmlWriter = Nothing
    Dim lwset As System.Xml.XmlWriterSettings = New Xml.XmlWriterSettings
    Dim floc As String = ""
    Dim path As String = Mwin.DS.StorStr & "Connection Libraries\" & _
             Mwin.ODBCCons.Text & " Library.xml"

    'Setup the writer settings
    Try
        lwset.Indent = True
        lwset.CloseOutput = True
        lwset.WriteEndDocumentOnClose = True
    Catch ex As Exception
        ErrBox("Failed to correctly configure the XML writer. The application " & _
        "will continue, but the XML file will not be as orderly. Error Details: " & _
        ex.Message, "ok", Mwin)
    End Try

    'Check if the file exists
    If System.IO.File.Exists(path) Then
        Try
            'Delete the existing file
            System.IO.File.Delete(path)
        Catch ex As Exception
            ErrBox("Failed to clear the current information from the library file." _
            & " Please reattempt the save. If that fails contact the administrator" _
            & " for this tool with the following error details: " & ex.Message, _
            "ok", Mwin)
            Exit Sub
        End Try
    End If

    'In all cases we now start writing the XML file
    Try
        floc = "writing the top level node of the XML document"
        'Start writing to a new version of the file
        lw = Xml.XmlWriter.Create(path)
        lw.WriteStartDocument()
        lw.WriteStartElement("Library")
        lw.WriteElementString("Database", Mwin.ODBCCons.Text)

        'Iterate through the schemas
        For Each s As SchObj In Mwin.DS.TblLib
            floc = "writing the schema level elements for the schema " & s.Name

            'Iterate through the tables
            For Each t As TblObj In s.Tables
                floc = "writing the table level elements for the table " & t.Name
                lw.WriteStartElement("Table")
                lw.WriteElementString("Name", t.Name)
                lw.WriteElementString("Desc", t.Desc)

                'iterate through the columns
                For Each c As ColObj In t.Cols
                    floc = "writing the column details for " & c.Name & " on table" _
                    & " " & t.Name
                    lw.WriteStartElement("Column")
                    lw.WriteElementString("Name", c.Name)
                    lw.WriteElementString("DB_Name", c.DbName)
                    lw.WriteElementString("Type", c.DType)
                Next

                'Relationships
                For Each r As RelObj In t.Rels
                    floc = "writing the relationship details for " & r.TableA & "-" _
                    & r.TableB & " on table " & t.Name
                    lw.WriteStartElement(r.TableB)
                    lw.WriteElementString("Key1", r.Key1)
                    lw.WriteElementString("Key2", r.Key2)
                    lw.WriteElementString("Key3", r.Key3)
                Next
            Next
        Next
    Catch ex As Exception
        ErrBox("An error was encountered while " & floc & ". Any information that " _
        & "had been output prior to this point will be saved, but the entirety of " _
        & "the table library may not be in the resultant XML file. Use caution " & _
        "when using this table library in the future." & Chr(10) & Chr(10) & _
        "This error does NOT impact the in-memory table library, and as such" & _
        " the application should continue to operate successfully." & Chr(10) & _
        Chr(10) & "Error Details: " & ex.Message, "ok", Mwin)
    End Try

    'Close the file (should implicitly save)
    Try
        lw.Close()
        lwset = Nothing
        lw = Nothing
    Catch ex As Exception
        ErrBox("Encountered an error while closing the library's save file. The " & _
        "application can continue to operate with the in-memory library, but there " _
        & "may be issues when the library is " _
               & "reloaded in the future. Error Details: " & ex.Message, "ok", Mwin)
    End Try
End Sub

1 个答案:

答案 0 :(得分:1)

您可以创建XmlWriterSettings对象并正确设置其属性:

Dim lwset As System.Xml.XmlWriterSettings = New Xml.XmlWriterSettings
' ...
lwset.Indent = True
lwset.CloseOutput = True
lwset.WriteEndDocumentOnClose = True

但是你从来没有在任何地方实际使用过这个对象。如果您将该设置对象作为参数传递给XmlWriter.Create方法,那么它将使用这些设置来确定它如何格式化输出:

lw = Xml.XmlWriter.Create(path, lwset)

我对它进行了测试,一旦我将设置对象传递给Create方法,它就会以所需的方式格式化XML。

对于它的价值,您可能希望使用现有的XML序列化工具之一,例如XmlSerializerDataContractSerializer,这些工具可以为您完成大部分工作。另外,您可能需要考虑为编写者使用Using关键字,而不是手动调用Close方法。