Vb.net 在创建第二个元素期间,XmlTextWriter以System.InvalidOperationException响应
XMLTextWriter.WriteStarteElement引发异常时遇到问题:Vb.net 在创建第二个元素期间,XmlTextWriter以System.InvalidOperationException响应,vb.net,xmltextwriter,Vb.net,Xmltextwriter,XMLTextWriter.WriteStarteElement引发异常时遇到问题: System.InvalidOperationException 尝试在XML文档中写入第二个元素时。此错误返回为。我还没有关闭它,所以我猜它已经超出了范围???我创建了一个类,使用XMLTextWriter作为类中的对象来编写XML文件。以下是相关代码。我发现另一篇关于这个问题的帖子从来没有得到过完全相同的回复。如有任何解决办法或其他建议,将不胜感激 Function CreateXML()... Try
System.InvalidOperationException
尝试在XML文档中写入第二个元素时。此错误返回为。我还没有关闭它,所以我猜它已经超出了范围???
我创建了一个类,使用XMLTextWriter作为类中的对象来编写XML文件。以下是相关代码。我发现另一篇关于这个问题的帖子从来没有得到过完全相同的回复。如有任何解决办法或其他建议,将不胜感激
Function CreateXML()...
Try
_listDocument = New XmlTextWriter(_xmlDI.FullName & "\\" & currentFilename, Nothing)
CreateHeader()
AddTimeDateNode()
CreateXML = True
Catch xmlErr As XmlException
MsgBox("Unable to create temporary file(" & currentFilename & ") that is used to change your whitelist or blacklist. " & _
"More technical information: " & xmlErr.Message, MsgBoxStyle.Critical, "Can't Continue")
End Try
End Function
Function AddListMember(ByVal listType As String, ByVal listItem As String, ByVal action As String) As Boolean
_listDocument.WriteStartElement(listItem) <-- CODE THROWS EXCEPTION HERE!
_listDocument.WriteAttributeString("listType", listType)
_listDocument.WriteAttributeString("action", action)
_listDocument.WriteString(listItem)
_listDocument.WriteEndElement()
_listDocument.WriteWhitespace(Chr(13) & Chr(10) & "\t")
Return True
End Function
'Sets the XML header
Private Function CreateHeader() As Boolean
_listDocument.WriteStartDocument(False)
_listDocument.WriteWhitespace(Chr(13) & Chr(10))
Return True
End Function
'Add Time Date node
Private Function AddTimeDateNode() As Boolean
_listDocument.WriteStartElement("DateTimeAdded")
_listDocument.WriteString(DateTime.Now.ToString)
_listDocument.WriteEndElement()
_listDocument.WriteWhitespace(Chr(13) & Chr(10))
Return True
End Function
据我所知,您似乎正在尝试创建多个根元素—一个用于
DateTimeAdded
,另一个用于列表成员
如果在CreateXml()
中调用writeStarteElement
,则最终会得到有效的XML。当然,您需要在结束文档之前结束该元素
(是的,codeguru的帖子看起来也在做同样的事情。)
基本上,这是一个有效的XML文档:
<RootElement>
<FirstElement>
Content
</FirstElement>
<SecondElement>
Content
</SecondElement>
</RootElement>
内容
内容
但这不是:
<FirstElement>
Content
</FirstElement>
<SecondElement>
Content
</SecondElement>
内容
内容
你试图做后者,因此出现了问题。谢谢Jon!这就是问题所在。
<FirstElement>
Content
</FirstElement>
<SecondElement>
Content
</SecondElement>