从字符串构建器创建xml文档将返回空文档

时间:2015-01-04 06:11:07

标签: asp.net xml vb.net

尝试使用字符串构建器创建am xml文档,如下所示。字符串生成器具有预期的精确值。但它不会写入xml文件。以下是代码

mssql = "select ID, ParentID, OrderID, Title, Start, End, PercentComplete, Expanded, Summary From Project"
        Dim buildXML As New StringBuilder
        buildXML.Append("<?xml version=""1.0"" encoding=""utf-8""?><Project>  <Tasks>")
        Dim mycommand As OdbcCommand
        mycommand = New OdbcCommand(mssql, dbcon)
        dbcon.Open()
        Dim reader As OdbcDataReader
        reader = mycommand.ExecuteReader
        While reader.Read
            buildXML.Append("<Task>" & _
            "<ID>1</ID>" & _
            "<ParentID />" & _
            "<Start>" & reader.Item("Start") & "</Start>" & _
            "<End>" & reader.Item("End") & "</End>" & _
            "<Title>" & reader.Item("Title") & "</Title>" & _
            "<PercentComplete>" & reader.Item("PercentComplete") & "</PercentComplete>" & _
            "<Summary>" & reader.Item("Summary") & "</Summary>" & _
            "<Expanded>" & reader.Item("Expanded") & "</Expanded>" & _
            "<OrderID>" & reader.Item("OrderID") & "</OrderID>" & _
            "</Task>")
        End While
        buildXML.Append("</Tasks>  <Dependencies /></Project>")
        reader.Close()
        dbcon.Close()

        'everything work fine up to this 

        Dim XMLDocument As System.Xml.XmlDocument = New System.Xml.XmlDocument()
        XMLDocument.LoadXml(buildXML.ToString())
        Dim Output As New XmlTextWriter(Server.MapPath("~/App_Data/gantt.xml"), System.Text.Encoding.UTF8)
        XMLDocument.WriteTo(Output)

保存文档会导致文档空白,有人知道原因吗?

1 个答案:

答案 0 :(得分:0)

请修改您的代码,如下所示:

1)从buildXML中删除Xml声明(xml版本和编码)。只有你的节点信息应该在那里。

2)修改您的注释代码,如下所示(使用Save而不是WriteTo)

Dim XMLDocument As System.Xml.XmlDocument = New System.Xml.XmlDocument()
XMLDocument.LoadXml(buildXML.ToString())
Dim Output As New XmlTextWriter(Server.MapPath("~/App_Data/gantt.xml"), System.Text.Encoding.UTF8)
XMLDocument.Save(Output)