在 VB.NET 中将字符串转换为 XML
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13805628/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
convert String to XML in VB.NET
提问by sanika
Dim filter As String
filter = 'Bal_ln_id = 110 and Bal_ln_id = 100'
Dim xmldoc As New System.Xml.XmlDocument
xmldoc.LoadXml(filter)
I am simply trying to convert a string in to xml file in VB.net.I am getting an xmlException 'Data at the root level is invalid. Line 1, position 1.'
我只是想将字符串转换为 VB.net 中的 xml 文件。我收到了 xmlException 'Data at the root level is invalid. Line 1, position 1.'
Am I missing something?
我错过了什么吗?
I am expecting the output as
我期待输出为
<DocumentElement>
<DATA_TABLE>
<BAL_LN_ID>110</BAL_LN_ID>
</DATA_TABLE>
<DATA_TABLE>
<BAL_LN_ID>100</BAL_LN_ID>
</DATA_TABLE>
</DocumentElement>'
回答by Steven Doggart
To do this using the XmlTextWriterclass, you could do something like this:
要使用XmlTextWriter该类执行此操作,您可以执行以下操作:
Private Function GenerateXml(ByVal ids As List(Of String)) As String
Dim stringWriter As New StringWriter()
Dim xmlWriter As New XmlTextWriter(stringWriter)
xmlWriter.WriteStartDocument()
xmlWriter.WriteStartElement("DocumentElement")
For Each id As String In ids
xmlWriter.WriteStartElement("DATA_TABLE")
xmlWriter.WriteStartElement("BAL_LN_ID")
xmlWriter.WriteString(id)
xmlWriter.WriteEndElement()
xmlWriter.WriteEndElement()
Next
xmlWriter.WriteEndElement()
xmlWriter.WriteEndDocument()
Return stringWriter.ToString()
End Function
Then you could use it like this:
然后你可以像这样使用它:
Dim ids As New List(Of String)()
ids.Add("110")
ids.Add("100")
Dim xml As String = GenerateXml(ids)

