473,587 Members | 2,494 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Serialize XML is broken?

I have the following code in a default.aspx web form page_load event. There
seems to be a problem with line 5 (NewsArticle.Da te = line).

//create a news article

NewsArticle NewsArticle = new NewsArticle();

NewsArticle.Bod y = "This is a test news article...";

NewsArticle.Tit le = "Testing XML";

NewsArticle.Dat e = Convert.ToDateT ime("4/3/2008");

NewsArticle.ID = "1";

//serialize the NewsArticle into an xml document

XmlDocument NewsArticleXml = new XmlDocument();

XmlSerializer Serializer = new XmlSerializer(N ewsArticle.GetT ype());

StringBuilder SB = new StringBuilder() ;

StringWriter Writer = new StringWriter(SB );

Serializer.Seri alize(Writer, NewsArticle);

NewsArticleXml. LoadXml(SB.ToSt ring());

Response.Clear( );

Response.Conten tType = "text/xml";

NewsArticleXml. Save(Response.O utput);

The result of the last line above in a web browser is this: Any idea where
the date attribute went? The NewsArticle object above was converted with xsd
from a schema to a class.

<?xml version="1.0" encoding="utf-8" ?>
- <NewsArticle xmlns:xsi="http ://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http ://www.w3.org/2001/XMLSchema" ID="1" Title="Testing XML">
<Body>This is a test news article...</Body>
</NewsArticle>
Jun 27 '08 #1
8 1993
Andy B wrote:
I have the following code in a default.aspx web form page_load event. There
seems to be a problem with line 5 (NewsArticle.Da te = line).

//create a news article

NewsArticle NewsArticle = new NewsArticle();

NewsArticle.Bod y = "This is a test news article...";

NewsArticle.Tit le = "Testing XML";

NewsArticle.Dat e = Convert.ToDateT ime("4/3/2008");

NewsArticle.ID = "1";

//serialize the NewsArticle into an xml document

XmlDocument NewsArticleXml = new XmlDocument();

XmlSerializer Serializer = new XmlSerializer(N ewsArticle.GetT ype());

StringBuilder SB = new StringBuilder() ;

StringWriter Writer = new StringWriter(SB );

Serializer.Seri alize(Writer, NewsArticle);

NewsArticleXml. LoadXml(SB.ToSt ring());

Response.Clear( );

Response.Conten tType = "text/xml";

NewsArticleXml. Save(Response.O utput);
I don't understand why you need the XmlDocument, you should simply let
the Serialize method write to Response.Output , no need for StringWriter
and XmlDocument.

The result of the last line above in a web browser is this: Any idea where
the date attribute went? The NewsArticle object above was converted with xsd
from a schema to a class.

<?xml version="1.0" encoding="utf-8" ?>
- <NewsArticle xmlns:xsi="http ://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http ://www.w3.org/2001/XMLSchema" ID="1" Title="Testing XML">
<Body>This is a test news article...</Body>
</NewsArticle>
Can you post the schema and the .NET code for NewsArticle?
--

Martin Honnen --- MVP XML
http://JavaScript.FAQTs.com/
Jun 27 '08 #2
You must be doing some custom serialization to get some properties as
attributes (id, title) and some as elements (body). The problem likely is in
your NewsArticle class.

"Andy B" wrote:
I have the following code in a default.aspx web form page_load event. There
seems to be a problem with line 5 (NewsArticle.Da te = line).

//create a news article

NewsArticle NewsArticle = new NewsArticle();

NewsArticle.Bod y = "This is a test news article...";

NewsArticle.Tit le = "Testing XML";

NewsArticle.Dat e = Convert.ToDateT ime("4/3/2008");

NewsArticle.ID = "1";

//serialize the NewsArticle into an xml document

XmlDocument NewsArticleXml = new XmlDocument();

XmlSerializer Serializer = new XmlSerializer(N ewsArticle.GetT ype());

StringBuilder SB = new StringBuilder() ;

StringWriter Writer = new StringWriter(SB );

Serializer.Seri alize(Writer, NewsArticle);

NewsArticleXml. LoadXml(SB.ToSt ring());

Response.Clear( );

Response.Conten tType = "text/xml";

NewsArticleXml. Save(Response.O utput);

The result of the last line above in a web browser is this: Any idea where
the date attribute went? The NewsArticle object above was converted with xsd
from a schema to a class.

<?xml version="1.0" encoding="utf-8" ?>
- <NewsArticle xmlns:xsi="http ://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http ://www.w3.org/2001/XMLSchema" ID="1" Title="Testing XML">
<Body>This is a test news article...</Body>
</NewsArticle>
Jun 27 '08 #3
Hi...

The XmlDocument was supposed to be created to make it easier to insert into
a database as an xml field. Is there any better way of doing this than what
was listed? I suppose I could just serialize to a string and insert that
into the database. Then load it as xml when it is needed. Anyways, here is
the schema and .net class for NewsArticle:

<?xml version="1.0" encoding="utf-8"?>

<xs:schema id="NewsArticle "

targetNamespace ="http://tempuri.org/NewsArticle.xsd "

elementFormDefa ult="qualified"

xmlns="http://tempuri.org/NewsArticle.xsd "

xmlns:mstns="ht tp://tempuri.org/NewsArticle.xsd "

xmlns:xs="http://www.w3.org/2001/XMLSchema"
>
<xs:element name="NewsArtic le">

<xs:complexType >

<xs:sequence>

<xs:element name="Body" type="xs:string " />

</xs:sequence>

<xs:attribute name="ID" type="xs:positi veInteger" />

<xs:attribute name="Title" type="xs:string " />

<xs:attribute name="Date" type="xs:dateTi me" />

</xs:complexType>

</xs:element>

</xs:schema>

using System.Xml.Seri alization;

[System.Serializ ableAttribute()]

[System.Xml.Seri alization.XmlRo otAttribute(IsN ullable=true)]

public partial class NewsArticle {
private string bodyField;

private string idField;

private string titleField;

private System.DateTime dateField;

private bool dateFieldSpecif ied;
public string Body {

get {

return this.bodyField;

}

set {

this.bodyField = value;

}

}
[System.Xml.Seri alization.XmlAt tributeAttribut e(DataType="pos itiveInteger")]

public string ID {

get {

return this.idField;

}

set {

this.idField = value;

}

}
[System.Xml.Seri alization.XmlAt tributeAttribut e()]

public string Title {

get {

return this.titleField ;

}

set {

this.titleField = value;

}

}
[System.Xml.Seri alization.XmlAt tributeAttribut e(DataType="Dat eTime")]

public System.DateTime Date {

get {

return this.dateField;

}

set {

this.dateField = value;

}

}
[System.Xml.Seri alization.XmlIg noreAttribute()]

public bool DateSpecified {

get {

return this.dateFieldS pecified;

}

set {

this.dateFieldS pecified = value;

}

}

}

"Martin Honnen" <ma*******@yaho o.dewrote in message
news:eu******** ******@TK2MSFTN GP03.phx.gbl...
Andy B wrote:
>I have the following code in a default.aspx web form page_load event.
There seems to be a problem with line 5 (NewsArticle.Da te = line).

//create a news article

NewsArticle NewsArticle = new NewsArticle();

NewsArticle.Bo dy = "This is a test news article...";

NewsArticle.Ti tle = "Testing XML";

NewsArticle.Da te = Convert.ToDateT ime("4/3/2008");

NewsArticle. ID = "1";

//serialize the NewsArticle into an xml document

XmlDocument NewsArticleXml = new XmlDocument();

XmlSerialize r Serializer = new XmlSerializer(N ewsArticle.GetT ype());

StringBuilde r SB = new StringBuilder() ;

StringWriter Writer = new StringWriter(SB );

Serializer.Ser ialize(Writer, NewsArticle);

NewsArticleXml .LoadXml(SB.ToS tring());

Response.Clear ();

Response.Conte ntType = "text/xml";

NewsArticleXml .Save(Response. Output);

I don't understand why you need the XmlDocument, you should simply let the
Serialize method write to Response.Output , no need for StringWriter and
XmlDocument.

>The result of the last line above in a web browser is this: Any idea
where the date attribute went? The NewsArticle object above was converted
with xsd from a schema to a class.

<?xml version="1.0" encoding="utf-8" ?>
- <NewsArticle xmlns:xsi="http ://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="htt p://www.w3.org/2001/XMLSchema" ID="1" Title="Testing XML">
<Body>This is a test news article...</Body>
</NewsArticle>

Can you post the schema and the .NET code for NewsArticle?
--

Martin Honnen --- MVP XML
http://JavaScript.FAQTs.com/

Jun 27 '08 #4
Andy B wrote:
[System.Serializ ableAttribute()]

[System.Xml.Seri alization.XmlRo otAttribute(IsN ullable=true)]

public partial class NewsArticle {
private string bodyField;

private string idField;

private string titleField;

private System.DateTime dateField;

private bool dateFieldSpecif ied;
public string Body {

get {

return this.bodyField;

}

set {

this.bodyField = value;

}

}
[System.Xml.Seri alization.XmlAt tributeAttribut e(DataType="pos itiveInteger")]

public string ID {

get {

return this.idField;

}

set {

this.idField = value;

}

}
[System.Xml.Seri alization.XmlAt tributeAttribut e()]

public string Title {

get {

return this.titleField ;

}

set {

this.titleField = value;

}

}
[System.Xml.Seri alization.XmlAt tributeAttribut e(DataType="Dat eTime")]

public System.DateTime Date {

get {

return this.dateField;

}

set {

this.dateField = value;

}

}
[System.Xml.Seri alization.XmlIg noreAttribute()]

public bool DateSpecified {

get {

return this.dateFieldS pecified;

}

set {

this.dateFieldS pecified = value;

}
With that class definition you need to set

NewsArticle.Dat eSpecified = true;

to have the Date field show up.

--

Martin Honnen --- MVP XML
http://JavaScript.FAQTs.com/
Jun 27 '08 #5
Family Tree Mike wrote:
You must be doing some custom serialization to get some properties as
attributes (id, title) and some as elements (body). The problem likely is in
your NewsArticle class.
Applying attributes to the properties isn't really custom serialization is it?

You can slap [XmlElement("pro perty1")] before a property, and have it serialize
as an actual element, and [XmlAttribute("p roperty2")] to have it serialize as an
attribute.

I'm not being critical here, just curious if that's considered custom
serialization. To my mind the point at which you need to write your own actual
serialization logic, rather than let .NET handle it, is the point at which it's
now custom serialization.

Chris.
Jun 27 '08 #6
Sounds like this might be more like custom xml document formatting more than
custom serialization.. ..
"Chris Shepherd" <ch**@nospam.ch sh.cawrote in message
news:us******** ******@TK2MSFTN GP04.phx.gbl...
Family Tree Mike wrote:
>You must be doing some custom serialization to get some properties as
attributes (id, title) and some as elements (body). The problem likely
is in your NewsArticle class.

Applying attributes to the properties isn't really custom serialization is
it?

You can slap [XmlElement("pro perty1")] before a property, and have it
serialize as an actual element, and [XmlAttribute("p roperty2")] to have it
serialize as an attribute.

I'm not being critical here, just curious if that's considered custom
serialization. To my mind the point at which you need to write your own
actual serialization logic, rather than let .NET handle it, is the point
at which it's now custom serialization.

Chris.

Jun 27 '08 #7
Ok setting NewsArticle.Dat eSpecified = true; did the job... tnx for the
help...
"Martin Honnen" <ma*******@yaho o.dewrote in message
news:ex******** ******@TK2MSFTN GP04.phx.gbl...
Andy B wrote:
>[System.Serializ ableAttribute()]

[System.Xml.Seri alization.XmlRo otAttribute(IsN ullable=true)]

public partial class NewsArticle {
private string bodyField;

private string idField;

private string titleField;

private System.DateTime dateField;

private bool dateFieldSpecif ied;
public string Body {

get {

return this.bodyField;

}

set {

this.bodyFie ld = value;

}

}
[System.Xml.Seri alization.XmlAt tributeAttribut e(DataType="pos itiveInteger")]

public string ID {

get {

return this.idField;

}

set {

this.idField = value;

}

}
[System.Xml.Seri alization.XmlAt tributeAttribut e()]

public string Title {

get {

return this.titleField ;

}

set {

this.titleFiel d = value;

}

}
[System.Xml.Seri alization.XmlAt tributeAttribut e(DataType="Dat eTime")]

public System.DateTime Date {

get {

return this.dateField;

}

set {

this.dateFie ld = value;

}

}
[System.Xml.Seri alization.XmlIg noreAttribute()]

public bool DateSpecified {

get {

return this.dateFieldS pecified;

}

set {

this.dateField Specified = value;

}

With that class definition you need to set

NewsArticle.Dat eSpecified = true;

to have the Date field show up.

--

Martin Honnen --- MVP XML
http://JavaScript.FAQTs.com/

Jun 27 '08 #8
Yes, that is what I should have said. What I meant was custom relative to
what the class would be without any attributes on the properties. That could
be done in a variety of ways, not having seen the code at that point.

"Andy B" wrote:
Sounds like this might be more like custom xml document formatting more than
custom serialization.. ..
"Chris Shepherd" <ch**@nospam.ch sh.cawrote in message
news:us******** ******@TK2MSFTN GP04.phx.gbl...
Family Tree Mike wrote:
You must be doing some custom serialization to get some properties as
attributes (id, title) and some as elements (body). The problem likely
is in your NewsArticle class.
Applying attributes to the properties isn't really custom serialization is
it?

You can slap [XmlElement("pro perty1")] before a property, and have it
serialize as an actual element, and [XmlAttribute("p roperty2")] to have it
serialize as an attribute.

I'm not being critical here, just curious if that's considered custom
serialization. To my mind the point at which you need to write your own
actual serialization logic, rather than let .NET handle it, is the point
at which it's now custom serialization.

Chris.


Jun 27 '08 #9

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

Similar topics

5
24689
by: David Sworder | last post by:
Hi, I've created a UserControl-derived class called MyUserControl that is able to persist and subsequently reload its state. It exposes two methods as follows: public void Serialize(Stream s); public void Deserialize(Stream s); Within the MyUserControl class, there is a field of type MyInnerClass
10
4140
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; string s_FinalFileName; try
3
10377
by: MAY | last post by:
Hi, I have a problem about serialize the form controls. I wrote a test program to test serialize a from but fail (->An unhandled exception of type 'System.Runtime.Serialization.SerializationException' occurred in mscorlib.dll) . Thx in advance. Here is the part of the code: Regards MAY
2
8872
by: films | last post by:
I understand the concept. Serialization of a class will add all the sub-objects of the class to the stream if there are also serializible. So say I have: class Author {
1
1468
by: js | last post by:
Does anybody knows how to solve the problem? I added attribute to the following classes in Microsoft.Practices.EnterpriseLibrary.Data namespace, but I still get the error. Thanks. Database.cs DatabaseFactory.cs DatabaseProviderFactory.cs DBCommandWrapper.cs
8
5443
by: cd~ | last post by:
I can provide a test app, the news server won't allow me to post the files because they are too large (93KB and 1.2KB) I downloaded the ESRI ArcXml schema and generated the classes from the schema using xsd.exe, which took a while because xsd doesn't handle recursive elements very well (StackOverFlow exception during generation). Now that I have the classes I am trying to serialize them to an xml document to send to ArcIMS to generate...
1
39682
by: Tim | last post by:
Could anyone tell me what this means and how do I correct it. Any suggestions? Thanks! Tim Richardson IT Developer and Consultant www.paladin3d.com Unable to serialize the session state. In 'StateServer' and 'SQLServer' mode, ASP.NET will serialize the session state objects, and as a result non-serializable objects or MarshalByRef objects are not permitted. The same
4
7110
by: =?Utf-8?B?Qnlyb24=?= | last post by:
When I try to serialize an instance of the LocationCell below (note Building field) I get an error in the reflection attempt. If I remove the _Building field it serializes fine. I tried renaming Building._Name to Building._BName in case the duplicate name was the issue, but that didn't help. Is there a native way to serialize nested objects, or will I have to write my own? public class LocationCell
9
1887
by: Gillard | last post by:
i get an exeption and i do not know what else to do to continue Dim sdf As New SaveFileDialog With sdf .AddExtension = True .DefaultExt = ".record" .FileName = Now.ToLongDateString .Filter = "recorder (*.record)|*.record" End With If sdf.ShowDialog = Windows.Forms.DialogResult.OK Then Dim Serializer As New
0
7924
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
7854
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8219
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8349
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
7978
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
6629
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
5722
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
3882
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1192
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.