XmlWriter不在VB.net中创建新元素

时间:2009-10-23 04:32:48

标签: xml vb.net xmlwriter

我正在使用VB.net写出一个XML文件。当我尝试创建另一个要写入第一个元素的元素时,它错误地说:

“状态EndRootElement中的Token StartElement将导致无效的XML文档。如果要编写XML片段,请确保将ConformanceLevel设置设置为ConformanceLevel.Fragment或ConformanceLevel.Auto。”

考虑到之前的元素已被关闭,我不确定为什么会这样做。我试图寻找一个writer.WriteEndRootElement,但我没有看到任何内容。任何建议让它工作? =)

    Private Sub writeXMLFile(ByVal childform As Fone_Builder_Delux.frmData, ByVal filename As String)

        Dim xmlSettings As New XmlWriterSettings()
        xmlSettings.Indent = True
        xmlSettings.NewLineOnAttributes = True

        Using writer As XmlWriter = XmlWriter.Create(filename, xmlSettings)

            writer.WriteStartDocument()
            writer.WriteStartElement("header")

            writer.WriteStartAttribute("filepath")
            writer.WriteValue(filename)
            writer.WriteEndAttribute()

            writer.WriteEndElement()
            writer.WriteStartElement("variable")
            writer.WriteStartAttribute("varName")

            writer.WriteValue(childform.datagridHeaders.Item(0, 1))

            writer.WriteEndAttribute()
            writer.WriteEndElement()
            writer.WriteEndDocument()
            writer.Flush()

        End Using


    End Sub

2 个答案:

答案 0 :(得分:6)

XML文档只能有一个根元素。您正在启动文档,编写“header”元素,关闭“header”元素,然后启动一个新的“variable”元素 - 这将是第二个根元素。

将“header”和“variable”括在一个更高级别的元素中,或将其中一个移到另一个元素中。

答案 1 :(得分:1)

您可以尝试这样的事情

 Private Sub writeXMLFile(ByVal childform As Fone_Builder_Delux.frmData, ByVal filename As String)

    Dim xmlSettings As New XmlWriterSettings()
    xmlSettings.Indent = True
    xmlSettings.NewLineOnAttributes = True

    Using writer As XmlWriter = XmlWriter.Create(filename, xmlSettings)

        writer.WriteStartDocument()
        writer.WriteStartElement("root")
        writer.WriteStartElement("header")

        writer.WriteStartAttribute("filepath")
        writer.WriteValue(filename)
        writer.WriteEndAttribute()

        writer.WriteEndElement()
        writer.WriteStartElement("variable")
        writer.WriteStartAttribute("varName")

        writer.WriteValue(childform.datagridHeaders.Item(0, 1))

        writer.WriteEndAttribute()
        writer.WriteEndElement()
        writer.WriteEndElement()
        writer.WriteEndDocument()
        writer.Flush()

    End Using


End Sub