XML Serialization without Attributes?

Hello,

I'm programming with Visual Studio 2005 for .net 2.0 in C#. Very often I
use XML Serilization [1].
Some of the output files can be edited by the user with an external
editor. What I don't like are some attributes which are inserted into
the fily by the serializer, and which may confuse the user.

Example:
| <?xml version="1.0"?>
| <Summary xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd = "http://www.w3.org/2001/XMLSchema">
|       <CurrentCQI>
|             <Incident>
|                   <CQI>
<snip>

I'd like to have something like that:
| <Summary>
|       <CurrentCQI>
|             <Incident>
|                   <CQI>
<snip>

The "?xml version" and xmlns attributes are not needed for
deserialization. XML files which were written manually without this
information are deserialized without problem.

Is there a possibility to tell the serializer to leave this data out of
the output file?

TIA,
Christian

[1] Here's the kind of code I use for serialization:

public object Data; // The object to be saved, set by a different method
private Type SType; // The type of the object
private FileStream DStream;    
private XmlSerializer XmlSer;  

SType = Data.GetType();         
XmlSer = new XmlSerializer(SType);    

DStream = new FileStream(p, FileMode.CreateNew);    
XmlSer.Serialize(DStream, Data);                    
0
11/7/2009 3:03:24 PM
dotnet.xml 7266 articles. 0 followers. Follow

3 Replies
2282 Views

Similar Articles

[PageSpeed] 42

Christian Treffler wrote:

> I'm programming with Visual Studio 2005 for .net 2.0 in C#. Very often I
> use XML Serilization [1].
> Some of the output files can be edited by the user with an external
> editor. What I don't like are some attributes which are inserted into
> the fily by the serializer, and which may confuse the user.
> 
> Example:
> | <?xml version="1.0"?>
> | <Summary xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd = "http://www.w3.org/2001/XMLSchema">
> |       <CurrentCQI>
> |             <Incident>
> |                   <CQI>
> <snip>
> 
> I'd like to have something like that:
> | <Summary>
> |       <CurrentCQI>
> |             <Incident>
> |                   <CQI>
> <snip>
> 
> The "?xml version" and xmlns attributes are not needed for
> deserialization. 

<?xml version="1.0"?> is not an attribute, it is the XML declaration. If 
you don't want that then serialize to an XmlWriter with the 
XmlWriterSettings specifying to omit the XML declaration e.g.

             XmlWriterSettings xws = new XmlWriterSettings();
             xws.OmitXmlDeclaration = true;
             xws.Indent = true;

             XmlSerializer ser = new XmlSerializer(typeof(Foo));

             using (XmlWriter writer = XmlWriter.Create(@"file.xml", xws))
             {
                 ser.Serialize(writer, fooInstance);
                 writer.Close();
             }
-- 

	Martin Honnen --- MVP XML
	http://msmvps.com/blogs/martin_honnen/
0
mahotrash (1777)
11/7/2009 4:46:55 PM
Christian Treffler wrote:

> I'm programming with Visual Studio 2005 for .net 2.0 in C#. Very often I
> use XML Serilization [1].
> Some of the output files can be edited by the user with an external
> editor. What I don't like are some attributes which are inserted into
> the fily by the serializer, and which may confuse the user.
> 
> Example:
> | <?xml version="1.0"?>
> | <Summary xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd = "http://www.w3.org/2001/XMLSchema">
> |       <CurrentCQI>
> |             <Incident>
> |                   <CQI>
> <snip>
> 
> I'd like to have something like that:
> | <Summary>
> |       <CurrentCQI>
> |             <Incident>
> |                   <CQI>
> <snip>
> 
> The "?xml version" and xmlns attributes are not needed for
> deserialization. XML files which were written manually without this
> information are deserialized without problem.

If you think you don't need them then you can get rid of the xmlns:xsi 
and xmlns:xsd attributes as follows:

             XmlSerializer ser = new XmlSerializer(typeof(Foo));
             XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
             ns.Add("", "");

             using (XmlWriter writer = XmlWriter.Create(@"file.xml", xws))
             {
                 ser.Serialize(writer, fooInstanceObject, ns);
                 writer.Close();
             }


-- 

	Martin Honnen --- MVP XML
	http://msmvps.com/blogs/martin_honnen/
0
mahotrash (1777)
11/7/2009 6:48:51 PM
Martin Honnen wrote:

> <?xml version="1.0"?> is not an attribute, it is the XML declaration. If 
> you don't want that then serialize to an XmlWriter with the 
> XmlWriterSettings
<snip>

Martin, thank you for your inputs. I implemented them and found that the
XmlWriterSettings provided some additional means to control the output. 
That was very useful.

Christian
0
11/9/2009 2:30:48 PM
Reply:

Similar Artilces:

Printing to PDF without margin loss or how to turn of print tiling
I have a full 8.5x11" flyer my printer is waiting for. The PDF I created is missing 1/4" around all sides......so I thought I would increase the paper size to 11x17". No margin problem here....Just the print tiling feature assumes everything is printed in 8.5x11 so I end up with 4 page PDFs...and my printer is still waiting. Any suggestions would be greatly appreciated Doug After managing to set up OE-QuoteFix on his new PC, Ed reads a message from Doug <anonymous@discussions.microsoft.com>... > I have a full 8.5x11" flyer my printer is waiting for. The PDF I...

Exchange 2003 Hangs without error
I have a Windows Server 2003 EE runing Exchange 2003. The server is part of a subdomain (mail.subdomain.domain.com). Essentailly what happens is that after a few days to a week, users are not able to login to the mail server. Outlook 2003 won't connect. Also when trying to connect via OWA it will pull up the login page, but after you hit submit it just sits. It doesn't seem to going on to open up the actual mailbox. Once you reboot the server, everything runs fine for a few more days. The server doesn't have any error in it's error logs to show what is wrong. We checked authen...

Condition-clause in XSLT using .Net System.Xml
Hi. I'm trying to execute a simple <xsl:if>-clause with a condition that reads: a<1 In MSXML 4 the clause <xsl:if test="a &lt; 1">do something...</xsl:if> works fine. But in .Net Xml it just doesn't work. I can't use the real character (<) because the XSLT wont be a valid XML. And if I use the encoded representation (&lt;) it wont compute at all. Anybody got a clue what to do??? // Magus - Il Dottore Magus wrote: > I'm trying to execute a simple <xsl:if>-clause with a > condition that reads: a<1 > In MSXML ...

Begginer question re pointers and serialization
Suppose I have an application with a document that contains a collection of objects, CTypedPtrList<CObList, CMyObjects*> Objects; and that the objects are created dynamically as the app runs. Further suppose that I want to reference these objects in another class via a pointer, class COtherClass : public CObject { protected: CMyObject* pObject; }; (DECLARE_SERIAL etc omitted for clarity). While the app runs, I'll be doing something like (pseudocode) // Create new object CMyObject* pMyObject = new CMyObject; Objects.AddTail(pMyObject); // Reference ...

sorting without affecting the format
Pls tell me how to sort out datas (A-Z or alphabetical oreder) without affecting the format (like spaces or rows in between). Any help would be greatly appreciated. Thank you. Sort the individual blocks separately (data without blanks), or else the space (blanks) will get sorted as well. HTH, Bernie MS Excel MVP "alyndejs" <alyndejs@discussions.microsoft.com> wrote in message news:7799C820-6BFE-4C45-894A-FA787089675D@microsoft.com... > Pls tell me how to sort out datas (A-Z or alphabetical oreder) without > affecting the format (like spaces or rows in between). An...

collating 3 columns into one without redundancy
Hi there. I've got 3 columns of names of domains, which are never the same, and want to create a list (or column) which takes these 3 columns and list the domains in order without redundancy (the same name could be up t 10 times, so that name should appear only once in the list) I've no idea how to do this, can anyone help? Regards, K -- Kashgarin ----------------------------------------------------------------------- Kashgarinn's Profile: http://www.excelforum.com/member.php?action=getinfo&userid=795 View this thread: http://www.excelforum.com/showthread.php?threadid=511...

Reporting without GAC assemblies?
I'm working on a portable application; one that runs from a USB drive. The only software requirements so far is that the .NET 2.0 Framework be installed. I want to include some reports. I'm familiar with SSRS, but I'm looking for something portable. I'm also familiar with Crystal Reports, but the runtime files may not be installed on the client and the user might not have permissions to install it. Therefore I'm left wondering if there are any tools out there that might be .NET based and inexpensive. Could anyone recommend some solutions that might work ...

Find serial number used
I�m forwarding this on from a user. <quote> We have 23 employees and 24 paid copies of Microsoft office. I need to install Office for a 24th person, an intern, using our last license. But... Given that I've been moving computers around recently and using Migration Assistant to move users around to different Macs, I've lost track of which license is free not being used (meaning, I have all of the retail Microsoft Office boxes and their respective serial #s, but don't know which one is not being used). I need to use the correct serial #, or Office gives me an error upon s...

Serial Number from Excel File
Hi, It;s possible to extract from a Excel File the Serial number from which this file has been created?? Or other property which determine truly the owner / creator of this Excel File. ...

XML save issue in .NET
Hi, Currently we are using the .NET XMLDocument Class to manipulate some xml documents. The issue we are having is that when we save the XML files using the classes save method, empty xml tags will be saved with a CRLF instead of the empty value. This can be solved by setting the PreserveWhiteSpace property to true. But then the indentation is lost. E.g.:- Before Saving this is how the tags are. <Test></Test> After saving <Test> </Test> Has anybody come across this, is there any solution for this. Thanks Amendra. Amendra wrote: > Currently we are using ...

Item Serial Numbers for Matrixed Items
Hello all: I have a question regarding serial numbers for matrixed items. I would like to set up an item, and then include a matrix for size, color, length, and still maintain invenotry on each color/sytle combination, and have a serial number for each item. Can anyone provide details as to how to best accomplish this. Thanks Victor Example: Style:FANA01 this comes in: Red, Green, Yellow and each color has small, med, large. Each item has a serial number. Create the item using the New Item Wizard as a matrix item. At the end of the wizard select "Edit this item" On t...

How to loop thru XML Schema and retrieve s the element name
Hi Folks, I need a sample to retieve all the element names from a XML schema using C#, I also total no of elements in the schema. Look at the XmlSchema and XmlSchemaElement classes on http://msdn.microsoft.com Alex "Mahesh" <Mahesh@discussions.microsoft.com> wrote in message news:EC45FD83-95A2-46F0-8BD6-CA30AE82C8CC@microsoft.com... > Hi Folks, > > I need a sample to retieve all the element names from a XML schema using > C#, > I also total no of elements in the schema. > > You can also take a look at the SOM article at http://www.xml.com/pub/...

Serial worker thread help
I have a serial worker thread that works with COM-DRV++(serial wrapper) below. This worked fine until I needed it to work under Vista. I have switched to the CreateFile(), ReadFile(), WriteFile() methods. UINT SerialThread( LPVOID Param ) //Thread to monitor serial activity { HWND hDlg = (HWND)Param; int DataByte=0x00; int Count=0; int i; while(TRUE){ Count=0; while(Count == 0){ Count = Port.BytesInReceiveBuffer(); Sleep(50); } DataByte=Port.GetByte(18); if (DataByte == 0x10){ for (i=0; i<33; i++){ DataByte=Port.GetByte(18); ...

Conversion of XmlText enum attributes
Hi there, I have an enum field that I serialize: [XmlAttribute("direction"), XmlText(typeof(ParameterDirection))] public ParameterDirection Direction = ParameterDirection.Out; The enum looks like this: public enum ParameterDirection { In, Out, Both }; In the generated XML, the value has to be lowercase. But, since "In" is a reserved word, I cannot have this as an enum value. How can I do this in a generic way? Any help appreciated, Thanks, Michel "Michel" <michel@nospam.nl> wrote in message news:c0sm13$4qd$1@reader11.wxs.nl... > public enum Param...

Convert excel file to xml
I need to convert excel data into an xml file. I use Excel 2003. Most help I can find suggests using an existing xml file to create an xml map, and then taking things from there. Since I haven't got as far as creating an xml file, I can't do that. Is there a simple way to convert excel data to an xml format? ...

help with serializing
hi, i am trying to serialize the following class : namespace MyNameSpace { [System.Xml.Serialization.XmlRootAttribute("StationData", Namespace="", IsNullable=false)] public class StationData { [System.Xml.Serialization.XmlElementAttribute("Station")] public Station[] Station; } public class Station { public int ID; [System.Xml.Serialization.XmlIgnoreAttribute()] public bool IDSpecified; public string Name; [System.Xml.Serialization.XmlElementAttribute("GameSets")] public GameSetData[] GameSets; } public class GameSetData { public int ID; ...

Removing all money attributes from entity causes troubles
Hi, I've come accross very weird behavior of CRM 4.0. I have a entity created with some money attributes on it. Later on we discovered that decimal attributes will suite us better so I removed all the money attributes (and created decimal attributes with the same names). CRM now can't create new entities throwing exceptions like this: Web Service Plug-in failed in OrganizationId: {Guid}; SdkMessageProcessingStepId: {Guid}; EntityName: new_testentity; Stage: 20; MessageName: Create; AssemblyName: Microsoft.Crm.ObjectModel.MultiCurrencyPlugin, Microsoft.Crm.ObjectModel, Versi...

Create a new workbook then rename without saving
Does anyone know if it is possible to open a new workbook and rename it without saving it using VBA? Even without opening it Dim OldName, NewName OldName = "OLDFILE" NewName = "NEWFILE" Name OldName As NewName -- HTH Bob Phillips (replace xxxx in the email address with gmail if mailing direct) "Graham Whitehead" <gwhitehead77@hotmail.com> wrote in message news:OKL6XE7jGHA.4508@TK2MSFTNGP05.phx.gbl... > Does anyone know if it is possible to open a new workbook and rename it > without saving it using VBA? > > This only works when I kn...

How do you reflect a salary increase without throwing out your budget?
Hi there I use Money2004 (too frightened to update to 05 given what I read here). I have created abudget tracking my income / expenses etc. How do I reflect the fact I've had a salary increase without messing up my past budget. For example, let's say my salary was $5000 per month. I start my budget in January and for the first six months it is $5K, then in June I get a raise to 7.5K per month. Money seems to want to project this 7.5K right the way back to January so it thinks I've been earning 7.5k the whole time - of course this throws everything out. The same thing happ...

Assembly Serial/Lot Entry Window
I'm building an assembly (food mfg plant), one component's lot number does not appear in the 'Available Serial/Lot' window (I'm FIFO - apparently it was used up in another build). What are the effects of typing in a NEW lot number? How will the new lot number be assigned a value? Will it screw up my inventory counts? Will it hose GL? I could just pick an available lot number, but I want to maintain accurate Lot trace-ability thru my finished goods to the component level. Any one have any idea? We're using Serial not lots and if you enter a new serial number a...

Problem: Attribute "border" exists, but can not be used for this element
hi asp.net 3.5 when validating my site I get the error mention in the subject of this post, here is the source code generating the problem. I mean thisis the source code taken from the browser: <span><input type="image" name="ctl00$Login2$LoginView1$Login1$Submit" id="ctl00_Login2_LoginView1_Login1_Submit" src="Images/Go.gif" alt="alt text is here" onclick="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(&quot;ctl00$Login2$LoginView1$Login1$Submit&quot;, &quot;&quot;, true, &...

How to email without all recipient's name appearing in the To fie.
How would I create a list like a distribution list and be able to email all on the list but without the entire list of names appearing in the To: field? I want one name in the To: field for each email. That would require a mail merge. Mail merge cannot use DL's. Outlook uses Word for performing mail merge functions such as Form Letters, mailing labels, envelopes, and fax or email merges. For an overview of these functions take a look here: http://www.slipstick.com/contacts/printlabel.htm http://www.outlook-tips.net/howto/mailmerge.htm -- Russ Valentine [MVP-Outlook] "Jeff&qu...

XML Linefeed question
Hi I posted this in the wrong ng yesterday, sry. I have my XMLDocument getting digitally signed with elements from my X509Certificate that I locate on the web server. This signing method is getting called by a classic website. The website I am sending this data to is looking a for a particular format of the X509Certificate element, in particular with line breaks intact. I've seen a few examples around the net where the X509Certificate has line breaks...I require this format for my app's receiving end. They say my xmldoc is getting signed ok with all the proper elements, b...

Retrieving Section & Tab of an Attribute.
Hi ng! I've been given the task to write a winforms app which exports all the attributes of all the entities with their postition on the form (tab & section). I can read all the attributes using the RetrieveAllEntities- Message, however I can't get the tab and/or section-names of any given attribute. Does anyone have a solution for that? Any help would be great. Regards Andreas Hi Andreas, This is not available in the metadata, you need to use the ExportXmlRequest for this. Something like this: ExportXmlRequest request = new ExportXmlRequest(); request.ParameterXml = "&l...

lead primary attribute should allow company name or fullname
When viewing activities, it is essential for many users to see quickly what company they are concerned with, couldn't the fullname attribute for the lead be set to either the company name or one of the first and last name options. -- Marge in the uk ---------------- This post is a suggestion for Microsoft, and Microsoft responds to the suggestions with the most votes. To vote for this suggestion, click the "I Agree" button in the message pane. If you do not see the button, follow this link to open the suggestion in the Microsoft Web-based Newsreader and then click "I...