XML Document and Errors in CDATA fields.

  • Thread starter Thread starter MarcoGG
  • Start date Start date
M

MarcoGG

Guest
Hi,

I'm writing a simple XML File with some data, including NON-AlphaNumeric Chars.

This is the code I use to create XML Document in memory and then write it to file :


Dim fullPathFileXML As String = Application.StartupPath & "\TEST.xml"

Dim XMLDoc As New Xml.XmlDocument

'XML Declaration
XMLDoc.AppendChild(XMLDoc.CreateXmlDeclaration("1.0", "utf-8", Nothing))

'<Rows> Root Tag
Dim xmlRoot As Xml.XmlNode = XMLDoc.CreateNode(Xml.XmlNodeType.Element,
String.Empty,
"Rows",
String.Empty)
XMLDoc.AppendChild(xmlRoot)

'Rows
Dim xmlRow As Xml.XmlNode
Dim cdataRow As Xml.XmlNode

'Row 1
xmlRow = XMLDoc.CreateNode(Xml.XmlNodeType.Element,
String.Empty,
"Row",
String.Empty)
cdataRow = XMLDoc.CreateNode(Xml.XmlNodeType.CDATA,
String.Empty,
"Row",
String.Empty)
cdataRow.InnerText = Convert.ToChar(20)
xmlRow.AppendChild(cdataRow)
xmlRoot.AppendChild(xmlRow)

'Row 2
xmlRow = XMLDoc.CreateNode(Xml.XmlNodeType.Element,
String.Empty,
"Row",
String.Empty)
cdataRow = XMLDoc.CreateNode(Xml.XmlNodeType.CDATA,
String.Empty,
"Row",
String.Empty)
cdataRow.InnerText = Convert.ToChar(21)
xmlRow.AppendChild(cdataRow)
xmlRoot.AppendChild(xmlRow)

'Other rows here ...
'...................
'...................

'Save XML File with XML Settings
Using MS As New System.IO.MemoryStream
Dim WS As New Xml.XmlWriterSettings
With WS
.Encoding = New System.Text.UTF8Encoding(False)
.ConformanceLevel = Xml.ConformanceLevel.Auto
.Indent = True
.CheckCharacters = False
End With
Dim XW As Xml.XmlWriter = Xml.XmlWriter.Create(MS, WS)
XMLDoc.Save(XW)
Dim xmlOutput As String = System.Text.Encoding.UTF8.GetString(MS.ToArray())
IO.File.WriteAllText(fullPathFileXML, xmlOutput)
End Using


And it works.
This is the expected XML File :


<?xml version="1.0" encoding="utf-8"?>
<Rows>
<Row><![CDATA[&#20;]]></Row>
<Row><![CDATA[&#21;]]></Row>
</Rows>


The Problem is all about loading the Document, and it gets Error :


Dim fullPathFileXML As String = Application.StartupPath & "\TEST.xml"
Dim strXml As String = IO.File.ReadAllText(fullPathFileXML)
Dim XMLDoc As New Xml.XmlDocument

Try

Using strReader As New IO.StringReader(strXml)
Dim xmlSettings As New Xml.XmlReaderSettings
xmlSettings.ConformanceLevel = Xml.ConformanceLevel.Auto
xmlSettings.CheckCharacters = False
xmlSettings.IgnoreComments = True
Dim xmlReader As Xml.XmlReader = Xml.XmlReader.Create(strReader, xmlSettings)
XMLDoc.Load(xmlReader)
End Using
Catch ex As Exception
MessageBox.Show(ex.Message,
"ERROR",
MessageBoxButtons.OK,
MessageBoxIcon.Exclamation)
End Try


Maybe some XML Settings I've mistaken or omitted...
Is there something I can do to keep it working with CDATA blocks ?

Thanks to everyone able to help.

Continue reading...
 
Back
Top