Serialize XML With Attributes Instead of Elements

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • grwalker@vt.edu

    Serialize XML With Attributes Instead of Elements

    I have some classes that have the <Serializable() > attribute applied,
    which of course by default serializes the class properties as elements.
    What I would like to do is to be able to override this behavior at
    runtime to serialize the properties as attributes.

    I have been exploring the XMLAttributesOv errides classes and examples
    which claims:

    "you can create one set of serializable classes, but serialize the
    objects in multiple ways. For example, instead of serializing members
    of a class instance as XML elements, you can serialize them as XML
    attributes, resulting in a more efficient document to transport."

    I have yet to be able to figure out how this can be acomplished
    however... For a simple class like the following if I call the
    SerializeXML() method I get an error.

    <Serializable() > _
    Public Class Class3

    Public Test As String = "Test"
    Private Test2 As String = "Test2"
    Private Test3 As String = "Test3"

    <XmlIgnore()> _
    Public Property Test4() As String
    Get
    Return Test3
    End Get
    Set(ByVal Value As String)
    Test3 = Value
    End Set
    End Property

    Public Sub SerializeXML(By Ref sw As TextWriter)
    Dim attrs As New XmlAttributes
    Dim attr As New XmlAttributeAtt ribute("MyTest" ,
    GetType(String) )
    attrs.XmlAttrib ute = attr

    Dim attrOverrides As New XmlAttributeOve rrides
    attrOverrides.A dd(Me.GetType, "Test", attrs)

    Dim xs As New XmlSerializer(G etType(Class3), attrOverrides)
    xs.Serialize(sw , Me)
    End Sub
    End Class

    Can someone PLEASE tell me how I can override the behavior at runtime
    to serialize as attributes instead of elelements.

  • Garry Freemyer

    #2
    Re: Serialize XML With Attributes Instead of Elements

    Oops. It might help a great deal if you told us what the error was. Sorry,
    but it's hilarious to me, I have done this mistake myself. I would think I
    would learn to state what the error I got was myself after groaning so many
    times when a user would tell me they forgot what the error was and what it
    was about and could not even remember enough about it to reproduce the
    error.
    :)
    <grwalker@vt.ed u> wrote in message
    news:1117902206 .591012.17460@g 14g2000cwa.goog legroups.com...[color=blue]
    >I have some classes that have the <Serializable() > attribute applied,
    > which of course by default serializes the class properties as elements.
    > What I would like to do is to be able to override this behavior at
    > runtime to serialize the properties as attributes.
    >
    > I have been exploring the XMLAttributesOv errides classes and examples
    > which claims:
    >
    > "you can create one set of serializable classes, but serialize the
    > objects in multiple ways. For example, instead of serializing members
    > of a class instance as XML elements, you can serialize them as XML
    > attributes, resulting in a more efficient document to transport."
    >
    > I have yet to be able to figure out how this can be acomplished
    > however... For a simple class like the following if I call the
    > SerializeXML() method I get an error.
    >
    > <Serializable() > _
    > Public Class Class3
    >
    > Public Test As String = "Test"
    > Private Test2 As String = "Test2"
    > Private Test3 As String = "Test3"
    >
    > <XmlIgnore()> _
    > Public Property Test4() As String
    > Get
    > Return Test3
    > End Get
    > Set(ByVal Value As String)
    > Test3 = Value
    > End Set
    > End Property
    >
    > Public Sub SerializeXML(By Ref sw As TextWriter)
    > Dim attrs As New XmlAttributes
    > Dim attr As New XmlAttributeAtt ribute("MyTest" ,
    > GetType(String) )
    > attrs.XmlAttrib ute = attr
    >
    > Dim attrOverrides As New XmlAttributeOve rrides
    > attrOverrides.A dd(Me.GetType, "Test", attrs)
    >
    > Dim xs As New XmlSerializer(G etType(Class3), attrOverrides)
    > xs.Serialize(sw , Me)
    > End Sub
    > End Class
    >
    > Can someone PLEASE tell me how I can override the behavior at runtime
    > to serialize as attributes instead of elelements.
    >[/color]


    Comment

    • grwalker@vt.edu

      #3
      Re: Serialize XML With Attributes Instead of Elements

      Garry,

      The error was "Error Reflecting Type" on line Dim xs As New
      XmlSerializer(G etType(Class3), attrOverrides). I didn't post the error
      message originally because I thought it was irrelevant in the context.
      All I want to know is if it is possible to control the serialization of
      properties at runtime as either elements or attributes using
      XMLAttributeOve rrides and how that can be done. My example is probably
      negligble as well, but I felt it necessary to throw *something* out
      there to give people some idea of what I was attempting. So... I doubt
      that error message is particularly helpful, but if you've got any ideas
      I'd be willing to listen.

      Garry Freemyer wrote:[color=blue]
      > Oops. It might help a great deal if you told us what the error was. Sorry,
      > but it's hilarious to me, I have done this mistake myself. I would think I
      > would learn to state what the error I got was myself after groaning so many
      > times when a user would tell me they forgot what the error was and what it
      > was about and could not even remember enough about it to reproduce the
      > error.
      > :)
      > <grwalker@vt.ed u> wrote in message
      > news:1117902206 .591012.17460@g 14g2000cwa.goog legroups.com...[color=green]
      > >I have some classes that have the <Serializable() > attribute applied,
      > > which of course by default serializes the class properties as elements.
      > > What I would like to do is to be able to override this behavior at
      > > runtime to serialize the properties as attributes.
      > >
      > > I have been exploring the XMLAttributesOv errides classes and examples
      > > which claims:
      > >
      > > "you can create one set of serializable classes, but serialize the
      > > objects in multiple ways. For example, instead of serializing members
      > > of a class instance as XML elements, you can serialize them as XML
      > > attributes, resulting in a more efficient document to transport."
      > >
      > > I have yet to be able to figure out how this can be acomplished
      > > however... For a simple class like the following if I call the
      > > SerializeXML() method I get an error.
      > >
      > > <Serializable() > _
      > > Public Class Class3
      > >
      > > Public Test As String = "Test"
      > > Private Test2 As String = "Test2"
      > > Private Test3 As String = "Test3"
      > >
      > > <XmlIgnore()> _
      > > Public Property Test4() As String
      > > Get
      > > Return Test3
      > > End Get
      > > Set(ByVal Value As String)
      > > Test3 = Value
      > > End Set
      > > End Property
      > >
      > > Public Sub SerializeXML(By Ref sw As TextWriter)
      > > Dim attrs As New XmlAttributes
      > > Dim attr As New XmlAttributeAtt ribute("MyTest" ,
      > > GetType(String) )
      > > attrs.XmlAttrib ute = attr
      > >
      > > Dim attrOverrides As New XmlAttributeOve rrides
      > > attrOverrides.A dd(Me.GetType, "Test", attrs)
      > >
      > > Dim xs As New XmlSerializer(G etType(Class3), attrOverrides)
      > > xs.Serialize(sw , Me)
      > > End Sub
      > > End Class
      > >
      > > Can someone PLEASE tell me how I can override the behavior at runtime
      > > to serialize as attributes instead of elelements.
      > >[/color][/color]

      Comment

      • grwalker@vt.edu

        #4
        Re: Serialize XML With Attributes Instead of Elements

        Does anyone have any idea how this:

        "you can create one set of serializable classes, but serialize the
        objects in multiple ways. For example, instead of serializing members
        of a class instance as XML elements, you can serialize them as XML
        attributes, resulting in a more efficient document to transport."

        can be accomplished?

        Comment

        • Chris Lovett

          #5
          Re: Serialize XML With Attributes Instead of Elements

          Try serializing this:

          Imports System.Xml
          Imports System.Xml.Seri alization

          Public Class Class1

          Public Name As String

          <XmlAttributeAt tribute()> _
          Public Id As Integer

          End Class

          <grwalker@vt.ed u> wrote in message
          news:1118144485 .045349.80790@o 13g2000cwo.goog legroups.com...[color=blue]
          > Does anyone have any idea how this:
          >
          > "you can create one set of serializable classes, but serialize the
          > objects in multiple ways. For example, instead of serializing members
          > of a class instance as XML elements, you can serialize them as XML
          > attributes, resulting in a more efficient document to transport."
          >
          > can be accomplished?
          >[/color]


          Comment

          • grwalker@vt.edu

            #6
            Re: Serialize XML With Attributes Instead of Elements

            Yes, I know that will work... But you missed the point. I want to
            control this behavior at runtime, not design time.

            Comment

            • DC

              #7
              Re: Serialize XML With Attributes Instead of Elements

              Yes, you can change serialization at runtime, to decide whether to serialize
              data as elements or attributes. There is a thing called XML Attribute
              overrides, that you can apply at runtime, when de-serializing.

              ---- Begin sample ----
              using System.IO;
              using System.Xml.Seri alization;

              namespace Ionic {


              public class Foo {
              public int id;
              public System.String name;
              public System.Single value;
              }


              /// <summary>
              /// helper class for serializing - omits the XML Declaration line (just
              for human readability)
              /// </summary>
              public class XmlTextWriterFo rmattedNoDeclar ation :
              System.Xml.XmlT extWriter {
              public XmlTextWriterFo rmattedNoDeclar ation (System.IO.Text Writer w) :
              base(w) { Formatting= System.Xml.Form atting.Indented ;}
              public override void WriteStartDocum ent () { }
              }


              public class TestDriver {
              public static void Main() {

              try {
              Foo x= new Foo();

              x.id= 7;
              x.name= "Theodore Roosevelt";
              x.value= 172.33F;

              XmlSerializer s1 = new XmlSerializer(t ypeof(Foo));
              XmlSerializerNa mespaces ns = new XmlSerializerNa mespaces();
              ns.Add( "", "" );


              System.Console. WriteLine("----------------------\nserialized as
              elements:\n");
              System.IO.Strin gWriter stringWriter = new System.IO.Strin gWriter();
              System.Xml.XmlW riter xmlWriter = new
              XmlTextWriterFo rmattedNoDeclar ation(stringWri ter);
              s1.Serialize(xm lWriter, x, ns);

              System.Console. WriteLine(strin gWriter.ToStrin g() + "\n\n");

              System.Console. WriteLine("----------------------\nserialized as
              attributes:\n") ;

              XmlAttributeOve rrides overrides = new XmlAttributeOve rrides();
              XmlAttributes attributeSet;
              XmlAttributeAtt ribute a1;

              // provide an Attribute attribute
              //
              Learn with interactive lessons and technical documentation, earn professional development hours and certifications, and connect with the community.

              a1 = new XmlAttributeAtt ribute("id");

              // drop that into an attribute Set
              attributeSet = new XmlAttributes() ;
              attributeSet.Xm lAttribute= a1;

              // add that attribute set for the first field
              overrides.Add(t ypeof(Foo), "id", attributeSet);

              // do the same thing for the name field
              a1 = new XmlAttributeAtt ribute("name");
              attributeSet = new XmlAttributes() ;
              attributeSet.Xm lAttribute= a1;
              overrides.Add(t ypeof(Foo), "name", attributeSet);

              // and finally, the same idea for the value field
              a1 = new XmlAttributeAtt ribute("value") ;
              attributeSet = new XmlAttributes() ;
              attributeSet.Xm lAttribute= a1;
              overrides.Add(t ypeof(Foo), "value", attributeSet);

              // create a new instance of the serializer specifying the overrides
              s1 = new XmlSerializer(t ypeof(Foo), overrides);

              // serialize as normal
              stringWriter = new System.IO.Strin gWriter();
              xmlWriter = new XmlTextWriterFo rmattedNoDeclar ation(stringWri ter);
              s1.Serialize(xm lWriter, x, ns);
              System.Console. WriteLine(strin gWriter.ToStrin g() + "\n\n");

              }
              catch (System.Excepti on e1) {
              System.Console. WriteLine("Exce ption!\n" + e1);
              }
              }
              }
              }

              ---- End sample ----

              -Dino
              dinoch // Microsoft.com

              <grwalker@vt.ed u> wrote in message
              news:1118243631 .648366.323190@ o13g2000cwo.goo glegroups.com.. .[color=blue]
              > Yes, I know that will work... But you missed the point. I want to
              > control this behavior at runtime, not design time.
              >[/color]


              Comment

              • grwalker@vt.edu

                #8
                Re: Serialize XML With Attributes Instead of Elements

                Ahh fantastic! This does indeed work! Apparently the only thing I was
                doing incorrectly in my code was attempting to pass a Type to the
                constructor of the XmlAttributeAtt ribute. I'm still not sure why this
                was causing the serialization to fail, but at least this works! Thanks
                much for the help!

                Comment

                Working...