XML Encoding woes...

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Terry Olsen

    #1

    XML Encoding woes...

    I use the following code to create an XML string:

    Private Sub Button1_Click(B yVal sender As System.Object, ByVal e As
    System.EventArg s) Handles Button1.Click
    Dim tw As New StringWriter
    Dim xml As New XmlTextWriter(t w)
    xml.WriteStartD ocument()
    xml.WriteStartE lement("StartEl ement")
    xml.WriteElemen tString("Elemen tString", "TheElement ")
    xml.WriteEndEle ment()
    xml.WriteEndDoc ument()
    xml.Close()
    MsgBox(tw.ToStr ing)
    End Sub

    This produces

    <?xml version="1.0" encoding="utf-16"?>
    <StartElement >
    <ElementString> TheElement</ElementString>
    </StartElement>

    I need the encoding to say "utf-8", but I can't get it to work.

    among other things, I've tried adding

    xml.Settings.En coding = New UTF8Encoding(Fa lse)

    directly after Dim'ing the xml object, but it throws the "Object reference
    not set to an instance" error.

    Need some guidance on this one.


  • GhostInAK

    #2
    Re: XML Encoding woes...

    Hello Terry,

    Look at the constructor overloads for XmlTextWriter.

    -Boo
    [color=blue]
    > I use the following code to create an XML string:
    >
    > Private Sub Button1_Click(B yVal sender As System.Object, ByVal e As
    > System.EventArg s) Handles Button1.Click
    > Dim tw As New StringWriter
    > Dim xml As New XmlTextWriter(t w)
    > xml.WriteStartD ocument()
    > xml.WriteStartE lement("StartEl ement")
    > xml.WriteElemen tString("Elemen tString", "TheElement ")
    > xml.WriteEndEle ment()
    > xml.WriteEndDoc ument()
    > xml.Close()
    > MsgBox(tw.ToStr ing)
    > End Sub
    > This produces
    >
    > <?xml version="1.0" encoding="utf-16"?>
    > <StartElement >
    > <ElementString> TheElement</ElementString>
    > </StartElement>
    > I need the encoding to say "utf-8", but I can't get it to work.
    >
    > among other things, I've tried adding
    >
    > xml.Settings.En coding = New UTF8Encoding(Fa lse)
    >
    > directly after Dim'ing the xml object, but it throws the "Object
    > reference not set to an instance" error.
    >
    > Need some guidance on this one.
    >[/color]


    Comment

    • Terry Olsen

      #3
      Re: XML Encoding woes...

      Yes, but they require that I write to a Stream, and not a StringWriter,
      which makes things a little more difficult. How can I use a Stream to write
      a string? I don't want to have to declare a large byte array.

      "GhostInAK" <ghostinak@gmai l.com> wrote in message
      news:c71747b447 2f8c855e22c497f 3e@news.microso ft.com...[color=blue]
      > Hello Terry,
      >
      > Look at the constructor overloads for XmlTextWriter.
      >
      > -Boo
      >[color=green]
      >> I use the following code to create an XML string:
      >>
      >> Private Sub Button1_Click(B yVal sender As System.Object, ByVal e As
      >> System.EventArg s) Handles Button1.Click
      >> Dim tw As New StringWriter
      >> Dim xml As New XmlTextWriter(t w)
      >> xml.WriteStartD ocument()
      >> xml.WriteStartE lement("StartEl ement")
      >> xml.WriteElemen tString("Elemen tString", "TheElement ")
      >> xml.WriteEndEle ment()
      >> xml.WriteEndDoc ument()
      >> xml.Close()
      >> MsgBox(tw.ToStr ing)
      >> End Sub
      >> This produces
      >>
      >> <?xml version="1.0" encoding="utf-16"?>
      >> <StartElement >
      >> <ElementString> TheElement</ElementString>
      >> </StartElement>
      >> I need the encoding to say "utf-8", but I can't get it to work.
      >>
      >> among other things, I've tried adding
      >>
      >> xml.Settings.En coding = New UTF8Encoding(Fa lse)
      >>
      >> directly after Dim'ing the xml object, but it throws the "Object
      >> reference not set to an instance" error.
      >>
      >> Need some guidance on this one.
      >>[/color]
      >
      >[/color]


      Comment

      • GhostInAK

        #4
        Re: XML Encoding woes...

        Hello Terry,
        As you no doubt noticed the XMLStringWriter ctor has an overload that takes
        a TextWriter. This is the only overload that does not take an Encoding parameter
        (besidesthe default ctor) because it is assumed that the TextWriter will
        implement the correct Encoding. TextWriter is declared MustInherit (Abstract
        in C#).

        So... Create a new class (I suggest naming it UTF8TextWriter) . Inherit from
        System.IO.TextW riter. You will have to implement the Encoding proeprty (which
        is declared MustOverride in the base). Return the correct Encoding (as a
        member variable (field)).

        Then pass an instance of this new class to the XMLStringWriter 's ctor. Presto,
        voila, abracadabra! :)

        Enjoy,
        -Boo
        [color=blue]
        > Yes, but they require that I write to a Stream, and not a
        > StringWriter, which makes things a little more difficult. How can I
        > use a Stream to write a string? I don't want to have to declare a
        > large byte array.[/color]


        Comment

        • Michel Posseth [MCP]

          #5
          Re: XML Encoding woes...

          I had this problem to ,,, so after some strugling i solved it like this

          i created a encodedstringwr iter

          here is my full implementation , use the parts you like / strip what you
          don`t need

          Imports System.Text
          Imports System.IO

          Namespace Text

          '''<summary>

          ''' Implementeerd een stringwriter waarbij je zelf de encoding kunt kiezen

          ''' de data wordt opgeslagen in een stringbuilder

          ''' </summary>

          Public Class EncodedStringWr iter

          Inherits StringWriter

          'Private property setter

          Private _Encoding As Encoding

          Public Sub New(ByVal sb As StringBuilder, ByVal Encoding As Encoding)

          MyBase.New(sb)

          _Encoding = Encoding

          End Sub

          ''' <summary>

          '''

          ''' </summary>

          ''' <value></value>

          ''' <doc>

          ''' <summary>gett er voor de string encoding </summary>

          ''' <returns>de Encoding waarin wordt geschreven </returns>

          ''' <filterpriority >1</filterpriority>

          ''' </doc>

          Public Overrides ReadOnly Property Encoding() As Encoding

          Get

          Return _Encoding

          End Get

          End Property

          End Class

          End Namespace


          Now in my XML base Class

          Option Explicit On
          Option Strict On

          Imports System.Xml

          Imports System.Text

          Imports System.IO

          Public MustInherit Class ClsXMLBase

          Public Structure XMLElement

          Dim ElementName As String

          Dim ElementValue As String

          End Structure

          Public Sub New()

          '-- default

          Init()

          End Sub

          Public Sub New(ByVal XMLRootName As String)

          RootNodeName = XMLRootName

          Init()

          End Sub

          Private Mvar_XMLDoc As XmlTextWriter

          Private Mvar_sb As StringBuilder

          Public Property ObjXML() As XmlTextWriter

          Get

          If IsNothing(Mvar_ XMLDoc) Then

          Init()

          End If

          Return Mvar_XMLDoc

          End Get

          Set(ByVal value As XmlTextWriter)

          Mvar_XMLDoc = value

          End Set

          End Property

          Private Mvar_RootNodeNa me As String = "MyRootnode "

          ''' <summary>

          ''' Getter Setter voor de rootnode naam

          ''' </summary>

          ''' <value>De naam van de rootnode .</value>

          Public Property RootNodeName() As String

          Get

          Return Mvar_RootNodeNa me

          End Get

          Set(ByVal value As String)

          Mvar_RootNodeNa me = value

          End Set

          End Property

          Public Overridable Sub Reset()

          Init()

          End Sub

          Private Sub Init()

          Mvar_sb = New StringBuilder(5 00)

          Mvar_XMLDoc = New XmlTextWriter(N ew Text.EncodedStr ingWriter(Mvar_ sb,
          Encoding.UTF8))

          Mvar_XMLDoc.For matting = Formatting.Inde nted

          Mvar_XMLDoc.Ind entation = 2

          Mvar_XMLDoc.Wri teStartDocument ()

          Mvar_XMLDoc.Wri teStartElement( RootNodeName)

          EndWritten = False

          End Sub

          ''' <summary>

          ''' sluit de instance van het XML object en alle onderliggende streams

          ''' </summary>

          Public Sub Close()

          Mvar_XMLDoc.Clo se()

          End Sub

          ''' <summary>

          ''' geeft de XML terug als een string

          ''' </summary>

          ''' <returns>stri ng data </returns>

          Public Function XMLToString() As String

          If Not EndWritten Then WriteEndDocumen t()

          Return Mvar_sb.ToStrin g

          End Function

          Private EndWritten As Boolean

          Private Sub WriteEndDocumen t()

          Mvar_XMLDoc.Wri teEndElement()

          Mvar_XMLDoc.Wri teEndDocument()

          EndWritten = True

          End Sub

          End Class



          and finally your worker class

          ption Explicit On

          Option Strict On

          Public Class clsYourWorkercl ass

          Inherits ClsXMLBase

          #Region " constructors "

          ''' <summary>

          ''' Initializeeerd een nieuwe instance van de class.

          ''' Overloaded

          ''' </summary>

          ''' <param name="RootNodeN ame">Naam van de rootnode ( standaard is NeProS )
          ..</param>

          Public Sub New(ByVal RootNodeName As String)

          MyBase.New(Root NodeName)

          End Sub

          #End Region

          ''' <summary>

          ''' Schrijft het XML document naar een file

          ''' </summary>

          ''' <param name="TargetPat h">het doel path (VB: C:\test.xml ) </param>

          Public Sub WriteXMLDocAsFi le(ByVal TargetPath As String)

          My.Computer.Fil eSystem.WriteAl lText(TargetPat h, MyBase.XMLToStr ing, False)

          End Sub



          End class


          use the mybase prefix to see all methods of the xml doc

          you have now a reusable xml document wich you can use with anny encoding you
          like


          regards

          Michel Posseth [MCP]


          "Terry Olsen" <tolsen64@hotma il.com> schreef in bericht
          news:%23GcnwABi GHA.3296@TK2MSF TNGP05.phx.gbl. ..[color=blue]
          > Yes, but they require that I write to a Stream, and not a StringWriter,
          > which makes things a little more difficult. How can I use a Stream to
          > write a string? I don't want to have to declare a large byte array.
          >
          > "GhostInAK" <ghostinak@gmai l.com> wrote in message
          > news:c71747b447 2f8c855e22c497f 3e@news.microso ft.com...[color=green]
          >> Hello Terry,
          >>
          >> Look at the constructor overloads for XmlTextWriter.
          >>
          >> -Boo
          >>[color=darkred]
          >>> I use the following code to create an XML string:
          >>>
          >>> Private Sub Button1_Click(B yVal sender As System.Object, ByVal e As
          >>> System.EventArg s) Handles Button1.Click
          >>> Dim tw As New StringWriter
          >>> Dim xml As New XmlTextWriter(t w)
          >>> xml.WriteStartD ocument()
          >>> xml.WriteStartE lement("StartEl ement")
          >>> xml.WriteElemen tString("Elemen tString", "TheElement ")
          >>> xml.WriteEndEle ment()
          >>> xml.WriteEndDoc ument()
          >>> xml.Close()
          >>> MsgBox(tw.ToStr ing)
          >>> End Sub
          >>> This produces
          >>>
          >>> <?xml version="1.0" encoding="utf-16"?>
          >>> <StartElement >
          >>> <ElementString> TheElement</ElementString>
          >>> </StartElement>
          >>> I need the encoding to say "utf-8", but I can't get it to work.
          >>>
          >>> among other things, I've tried adding
          >>>
          >>> xml.Settings.En coding = New UTF8Encoding(Fa lse)
          >>>
          >>> directly after Dim'ing the xml object, but it throws the "Object
          >>> reference not set to an instance" error.
          >>>
          >>> Need some guidance on this one.
          >>>[/color]
          >>
          >>[/color]
          >
          >[/color]


          Comment

          Working...