On 15 Jun, 15:09, Martin Honnen <mahotr...@yahoo.dewrote:
JB wrote:
I'm having problems with Tab characters in an XML file.
I want to store a Tab character as part of an element value e.g.
<Separator>TAB</Separator>
I'm using XmlWriter to write my file and XmlReader to read it.
At first my tab character was stored in the element, but was ignored
when it was read back (giving me an empty string as a content).
Can you show us your code? I can't reproduce the problem, the following
test code
Dim fileName As String = "..\..\XmlTest1.xml"
Dim writerSettings As New XmlWriterSettings()
writerSettings.Indent = True
Using writer As XmlWriter = XmlWriter.Create(fileName,
writerSettings)
writer.WriteStartDocument()
writer.WriteStartElement("root")
writer.WriteStartElement("foo")
writer.WriteElementString("bar", ChrW(9).ToString())
writer.WriteEndDocument()
End Using
Using reader As XmlReader = XmlReader.Create(fileName)
While reader.Read()
If reader.NodeType = XmlNodeType.Element And
reader.LocalName = "bar" Then
Dim bar As String = reader.ReadString()
Console.WriteLine("|{0}|", bar)
Console.WriteLine(bar = ChrW(9).ToString())
End If
End While
End Using
results in the output
| |
True
suggesting that the tab character is written and read back.
Make sure you don't use an XmlReader with XmlReaderSettings where
IgnoreWhitespace is set to True as in that case the tab would be ignored.
--
Martin Honnen --- MVP XML
http://JavaScript.FAQTs.com/
Hi All,
Thanks for all your suggestions.
Following Martin's code I isolated the problem.
I read my file sequentially and I use the function
ReadElementContentAsString.
If I write the file without indentation, ReadElementContentAsString
works fine.
If I write the file with indentation, ReadElementContentAsString
causes an exception: "'Whitespace' is an invalid XmlNodeType. Line 3,
position 8."
I don't really want to have to rewrite all my code to look like Method
2, so I'm thinking that it might be simpler to escape all my string
contents to transform any special character into the escaped version.
Is there an option to do this automatically for my entire XML file or
do I have to do it "manually" for each field with some sort of
replace?
See my code below:
Using reader As XmlReader = XmlReader.Create(fileName)
reader.ReadStartElement("root")
reader.ReadStartElement("foo")
'Method 1 - Doesn't work
' Dim bar As String = reader.ReadElementContentAsString("bar",
"")
'Method 2 - Works!
reader.Read()
Debug.Assert(reader.NodeType = XmlNodeType.Element And
reader.LocalName = "bar")
Dim bar As String = reader.ReadString()
Console.WriteLine("|{0}|", bar)
Console.WriteLine(bar = ChrW(9).ToString())
reader.ReadEndElement()
reader.ReadEndElement()
End Using