473,373 Members | 1,188 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,373 software developers and data experts.

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 XMLAttributesOverrides 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(ByRef sw As TextWriter)
Dim attrs As New XmlAttributes
Dim attr As New XmlAttributeAttribute("MyTest",
GetType(String))
attrs.XmlAttribute = attr

Dim attrOverrides As New XmlAttributeOverrides
attrOverrides.Add(Me.GetType, "Test", attrs)

Dim xs As New XmlSerializer(GetType(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.

Nov 12 '05 #1
7 4321
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.
:)
<gr******@vt.edu> wrote in message
news:11*********************@g14g2000cwa.googlegro ups.com...
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 XMLAttributesOverrides 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(ByRef sw As TextWriter)
Dim attrs As New XmlAttributes
Dim attr As New XmlAttributeAttribute("MyTest",
GetType(String))
attrs.XmlAttribute = attr

Dim attrOverrides As New XmlAttributeOverrides
attrOverrides.Add(Me.GetType, "Test", attrs)

Dim xs As New XmlSerializer(GetType(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.

Nov 12 '05 #2
Garry,

The error was "Error Reflecting Type" on line Dim xs As New
XmlSerializer(GetType(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
XMLAttributeOverrides 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:
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.
:)
<gr******@vt.edu> wrote in message
news:11*********************@g14g2000cwa.googlegro ups.com...
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 XMLAttributesOverrides 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(ByRef sw As TextWriter)
Dim attrs As New XmlAttributes
Dim attr As New XmlAttributeAttribute("MyTest",
GetType(String))
attrs.XmlAttribute = attr

Dim attrOverrides As New XmlAttributeOverrides
attrOverrides.Add(Me.GetType, "Test", attrs)

Dim xs As New XmlSerializer(GetType(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.


Nov 12 '05 #3
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?

Nov 12 '05 #4
Try serializing this:

Imports System.Xml
Imports System.Xml.Serialization

Public Class Class1

Public Name As String

<XmlAttributeAttribute()> _
Public Id As Integer

End Class

<gr******@vt.edu> wrote in message
news:11*********************@o13g2000cwo.googlegro ups.com...
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?

Nov 12 '05 #5
Yes, I know that will work... But you missed the point. I want to
control this behavior at runtime, not design time.

Nov 12 '05 #6
DC
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.Serialization;

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 XmlTextWriterFormattedNoDeclaration :
System.Xml.XmlTextWriter {
public XmlTextWriterFormattedNoDeclaration (System.IO.TextWriter w) :
base(w) { Formatting= System.Xml.Formatting.Indented;}
public override void WriteStartDocument () { }
}
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(typeof(Foo));
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add( "", "" );
System.Console.WriteLine("----------------------\nserialized as
elements:\n");
System.IO.StringWriter stringWriter = new System.IO.StringWriter();
System.Xml.XmlWriter xmlWriter = new
XmlTextWriterFormattedNoDeclaration(stringWriter);
s1.Serialize(xmlWriter, x, ns);

System.Console.WriteLine(stringWriter.ToString() + "\n\n");

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

XmlAttributeOverrides overrides = new XmlAttributeOverrides();
XmlAttributes attributeSet;
XmlAttributeAttribute a1;

// provide an Attribute attribute
//
http://msdn.microsoft.com/library/en...ClassTopic.asp
a1 = new XmlAttributeAttribute("id");

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

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

// do the same thing for the name field
a1 = new XmlAttributeAttribute("name");
attributeSet = new XmlAttributes();
attributeSet.XmlAttribute= a1;
overrides.Add(typeof(Foo), "name", attributeSet);

// and finally, the same idea for the value field
a1 = new XmlAttributeAttribute("value");
attributeSet = new XmlAttributes();
attributeSet.XmlAttribute= a1;
overrides.Add(typeof(Foo), "value", attributeSet);

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

// serialize as normal
stringWriter = new System.IO.StringWriter();
xmlWriter = new XmlTextWriterFormattedNoDeclaration(stringWriter);
s1.Serialize(xmlWriter, x, ns);
System.Console.WriteLine(stringWriter.ToString() + "\n\n");

}
catch (System.Exception e1) {
System.Console.WriteLine("Exception!\n" + e1);
}
}
}
}

---- End sample ----

-Dino
dinoch // Microsoft.com

<gr******@vt.edu> wrote in message
news:11**********************@o13g2000cwo.googlegr oups.com...
Yes, I know that will work... But you missed the point. I want to
control this behavior at runtime, not design time.

Nov 12 '05 #7
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 XmlAttributeAttribute. I'm still not sure why this
was causing the serialization to fail, but at least this works! Thanks
much for the help!

Nov 12 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
by: Joris Gillis | last post by:
Hi everyone, I was wondering... Can one element have multiple (identically named) attributes in XML? e.g. Is the following document valid XML? <?xml version="1.0" encoding="UTF-8"?> <root...
2
by: Hollywood | last post by:
After doing a search through google's archives of this list, I didn't see what I was looking for so here goes... Is it possible to serialize/deserialize multiple objects from a single XML file? ...
10
by: Dan | last post by:
All I Am Attempting To Serialize An Object To An XML File. Here Is The Code For That public string SaveNewSurvey( MutualSurveyObject mso_TempObject, int i_JobID ) { string s_RootFileName;...
3
by: Peter Cresswell | last post by:
Hello everyone, I would like to serialize an object to XML. Currently my code will serialize all of the public properties that are value types, but not my public properties that have get...
4
by: teddysnips | last post by:
I would like to serialize a class to XML. The format of the XML is fixed (see below). It only needs to be serialized - it is read by another application. I know I can do it manually using...
0
by: RogerD | last post by:
Hello All, I have a custom class (Collar) that is a property of another custom class (Dog) which inherits from (Animal). I want to serialize Dog and have the properties from Collar appear as...
0
by: David Lozzi | last post by:
Howdy, I just had a small explosion in my brain, and now i'm a little more confused than I was before. I'm fairly new to XML, but understand it for the most part in regards to formatting. I have...
0
by: jeoffh | last post by:
Background: I am trying to "merge" some attributes into an existing XML column in my MS SQL 2005 database. The general idea is that I have an XML column in a table and I would like to update/delete...
8
by: Andy B | last post by:
I have the following code in a default.aspx web form page_load event. There seems to be a problem with line 5 (NewsArticle.Date = line). //create a news article NewsArticle NewsArticle = new...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.