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
2374 Views

Similar Articles

[PageSpeed] 3

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:

XML samples for replace a child element
Hi, Does anybody know where I can find samples to search an element in a subtree of an xml file and replace some new value for this element? I can only find some samples to use 'replace last child or replade first child' but couldn't find sample for replace a child neither first nor last child. Thanks for any help, CT See http://msdn.microsoft.com/library/en-us/cpref/html/frlrfSystemXmlXmlNodeClassReplaceChildTopic.asp Rather than specifying root.FirstChild or root.LastChild, you only need to select a particular node. Supposing you have the root node of the dom document (r...

Error when adding an Attribute i CRM 3.0
Hi. I know this is a long shot, and it can be a million things. But suddenly I can't add Custom Attributes to the database. The dialog after "save" is: "An error has occurred. For more information, contact your system administrator". I have set the "<add key="DevErrors" value="On"/>" and hoped that the dialog box would tell me more. But I got the same message. There is no problem in adding existing fields to existing forms, and I can publish then without any problems. Any ideas? Best regards and thanks for your h...

Attribute targetNamespace does not match the designated namespace
Hi you all. I've got a problem validating an XML file using the following Schema (I'll post only the beginning of this): ---------------------------------------------------------------------------- <?xml version="1.0" encoding="utf-8"?> <xs:schema xmlns="http://tempuri.org/ae" elementFormDefault="qualified" targetNamespace="http://tempuri.org/ae" xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="FileContratti"> <xs:complexType> .... (to be continue)... ---------------...

recover domain user password without the domain.
Hello, I have a client that has a company laptop, and he has forgotten his password. Now the laptop was part of an old business with a domain that no longer exists. What can I do to recover the password. I have access to the local admin account, but not the domain admin account on the laptop. Domain was with a sbs 2003 machine. You cannot recover domain password without a domain controller. If you have access to the local admin account, you can unjoin computer from the domain. Then create a local user account and let the owner use this new local account. "Don"...

v2003 XML Map, Enumeration to drop-down list
I have XSD files with enumerations to constrain the value of specific elements. I want to use Excel to enter data using the XSD. When I apply the XSD as an XML Map I can assign a cell to each element and create a List which will get exported as an XML document. All good so far. For the cells that are constrained, if I don't enter a proper enumerated value into a cell, when I export I get a message like this: 'element' violates enumeration constraint of 'a b c d e'. The element {URIpath}Name with value 'foo' failed to parse. If I ensure that I enter correct case-...

Dataset.WriteXml does NOT produce well formed XML
For example: =========================== Dim filename As String filename = Server.MapPath("./") & "xml/dataSet.xml" Dim myFileStream As New System.IO.FileStream(filename, IO.FileMode.Create) Dim myXmlWriter As New System.Xml.XmlTextWriter (myFileStream, System.Text.Encoding.Unicode) objDataSet.WriteXml(myXmlWriter) myXmlWriter.Close() ============================ Thus, if there is data in the dataset with a string such as: "Where are my < & > ESCAPE sequences?" The resulting XML will look like: <foo>Where are my < & > ESCAP...

outlook 2003 keeps dying without giving me a real error message
i recently upgraded from outlook 2000 to 2003. i'm now getting the following error when i'm done downloading roughly 1/2 to 3/4 of my email: Task 'mail.mydomain.com - Receiving' reported error (0x800CCC90) : 'Your incoming (POP3) e-mail server has reported an internal error. If you continue to receive this message, contact your server administrator or Internet service provider (ISP). The server responded: .' there's never anything in the "The server responded..." section. once it dies, it seems to forget that it's already downloaded a bunch of the ...

Signed-signed xml-doc and xsd
Hi, I�m a bit of a newbie when it comes to xml but here goes: I am using the SignedXml-class to construct a signed xmldoc which in turn contains 1 or more signed xml-doc which creates the following structure (edited of course): <Signature xmlns:xd="Whatever"> <Object Id="A uri"> <Signature> <Object Id="Another uri">My data</Object> </Signature> </Object> </Signature> My problem occurrs when try to use xsd.exe to create a schema for this. I get the fol...

Xml web services step by step tutorial
Hi all, I am a newbie for web service and i would like to develop the web service directory like uddi or strikeiron.com based on the web service technology. COuld any one show me step by step to do so, what i really need to know and how to do so. THank you so much. A really great book is Professional ASP.NET Web Services with VB.Net by Wrox "Popoxinhxan" <Popoxinhxan@discussions.microsoft.com> wrote in message news:E99E9635-D5A1-42A7-B8F0-6139356E98E1@microsoft.com... > Hi all, > I am a newbie for web service and i would like to develop the web service directory like ...

Accessing SAP WAS via SOAP / xml-namespace problem
hello everybody, I want to call a method on a SAP WAS. For testing purposes, I do have the same method on two WASs. One of them has been updated recently. The wsdl-files of both are not identical from a text point of view, however, from the xml-point of view they are (one declares all types inline, the other by type-attributes and subsequent definition). so, no wonder at all, both of them result in identical c#-proxyclasses after applying the wsdl.exe. the problem is, it works fine with one server, i.e. after calling 'invoke' in the proxyclass, I get an object arry with two non-null ...

Find the depth of XML
I have following XML: How can I find the depth of XML? in other word max level of the XML <Root> ----- level 0 <Name>----- level 1 <FirstName>name</FirstName> ---- level 2 <LasName>lname</LastName> <MiddleName>mName<MiddleName> </Name> <Information> <Info1> <Info2> --- level 3 <Info3>asdasd</Info> -- level 4 </Info2> </Info1> </Information> </Root> Raed Sawalha wrote: > I have following XML:...

XML with chinese character problem
In my .net ,i need to generate an xml file , however, user may input a chinese character, Then , the xml will got something unknow characters. the following is my code, Does anyone know how to solve it ?? Private Sub Init() With AMSXML ..Formatting = Formatting.Indented ..Indentation = 4 ..IndentChar = " " ..WriteStartDocument() ..WriteDocType("SOGenericInterchange", Nothing, "SOGenericInterchange.dtd", Nothing) ..WriteStartElement("SOGenericInterchange") End With End Sub Private Sub InterchangeHeaderIdentification() Try With AMSXML ..WriteStartElemen...

ANNOUNCE: v2007 of Altova XML software available
Altova is pleased to announce the availability of Version 2007 of its XML product line. Version 2007 provides numerous new features and updates, including a revolutionary new WSDL editor in XMLSpy=C2=AE, the ability to use Web services as sources, targets, or functions in MapForce=C2=AE data integration projects, output sorting in StyleVision=C2= =AE, a major speed increase in the AltovaXML=E2=84=A2 processor built into the products, and much more. In addition, limited time offers allow customers to save up to 52% when they upgrade to XMLSpy 2007 from an older version, or get a free license fo...

howto: convert from xml to text ?
Hi, If anyone knows how to convert a input xml (getting from a url querry) and convert it into a flat, csv text file ?? Thanks, Gopi hmm... but can you point some examples...?? Thanks, Gopi "Dimitre Novatchev" <dnovatchev@yahoo.com> wrote in message news:be7d6s$235oo$1@ID-152440.news.dfncis.de... > This can be done using XSLT. > > > ===== > Cheers, > > Dimitre Novatchev. > http://fxsl.sourceforge.net/ -- the home of FXSL > > > > "Gopinath Varadharajan" <vgopinath@hotmail.com> wrote in message > news:exXDxHzQDHA.402...

XML Request & Response & ASP.NET 2.0
Hi, I would like to know like in ASP.NET 2.0 or .net version 2.0, how do I parse the XML and consume it?. right now I am using the old methods like XML DOM. second thing is I need to send a XML Request to some URL, inturn I will be getting the response Back in the form of XML ONLY. HOW TO SEND THE XML request in Version 2.0? I am using old method like HttpWebRequest & HttpWebResponse bye thanks, ss ss wrote: > I would like to know like in ASP.NET 2.0 or .net version 2.0, how do I parse > the XML and consume it?. > > right now I am using the old methods like XML...

Importing ADO Persisted XML into Excel 2002
Is it possible to take a ADO.Recordset, which is persisted to XML and import that into Excel 2002 ? I'm using VB/VBA/VBS. I can find a range on a worksheet, and export it to MSPersist format pretty easy, so I assume the reverse can be done ? If so, does anyone have any sample code ? gadrin7@aol.com wrote: > Is it possible to take a ADO.Recordset, which is persisted to XML and > import that into Excel 2002 ? You should be able to just open it in Excel, it should render it somehow. You could re-open the recordset using ADO in VBA code then use Excel's CopyFromRecordset metho...

How to open workbook without hardcoding path
Hi Could anyone tell me how to open a workbook from another workbook, where both files are in the same folder, without hardcoding the path. I have tried code like this without success. Workbooks.open (path & "\somefile.xls") Thanks in advance Mick Excel automatically looks in the current folder, so :- Workbooks.open "somefile.xls ----------------------------------------------- ~~ Message posted from http://www.ExcelTip.com ~~View and post usenet messages directly from http://www.ExcelForum.com ...

Serial Reference Creation SO
In a HQ Environment - Store Operations for all areas applicable should use as a prefix to reference creation the store ID from dbo.Configuration. This then provides HQ with data that is acurate to each store. I have requested this as I have found that pretty well much no information about stocktakes gets to head office (HQ) - so I am doing this via Tablesync (it has it's own issues) and seems to work to the most part. However I do find that since you can name your own reference number then there 'could' be the possibility of an error in soem form - human or otherwise. If ...

why I can serialize a class without using [Serializable]?
I have written a class in C# and I have serilized into a file .I read somewhere that if you want a class to be serializble you must add an attribute called [Serializable] before the class and within the namespace,I didn't do that but I could serialize it using the following code: try { XmlSerializer s = new XmlSerializer( typeof( EnviroVars) ); s.Serialize( fs, enviromental_Vars ); } catch(Exception ee) { MessageBox.Show(ee.Message + "**" + ee.StackTrace + "**" + ee.Source); } finally { fs.Close(); } thanks for your help [Serializable] is for runtime s...

SP returning XML
Can someone give me an example of how to use a stored procedure that returns XML data? I want to call the SP from a VBScript program, and put the XML into a data island in the generated HTML. Peter Morris wrote: > Can someone give me an example of how to use a > stored procedure that returns XML data? > > I want to call the SP from a VBScript program, > and put the XML into a data island in the generated HTML. Do you mean a procedure that runs a query containing a FOR XML clause? Bob Barrows -- Microsoft MVP - ASP/ASP.NET Please reply to the newsgroup. This email acco...

XSLTransform & using XML Resolver to get images
I am transforming xml using XSLTransform which works fine. The xsl file is stored on eg. C:\temp1 and the xml is loaded from c:\temp2. All image files referenced in the stylesheet file are stored on the same path as the stylesheet and are not used in the transform. How do I use an XMLResolver to transform using the images without having to move the files, is it possible??? Images are referenced as eg. <img src="image1.gif"/> in the stylesheet. Thanks * Pat Buxton wrote in microsoft.public.dotnet.xml: >I am transforming xml using XSLTransform which works fine. The xsl >...

xpointer within a xml called by xinclude
Is it possible to have a xpointer attribute inside a xml file called from a xinclude attribute. eg: FileA.xml <xi:include href="FileB.xml" /> FileB.xml <xi:include href="FileC.xml" xpointer="xpointer(//NodeB)" /> FileC.xml <Root> <NodeA>NodeA Content</NodeA> <NodeB>NodeB Content</NodeB> </Root> I can reference the node if I put a xpointer in FileA eg: <xi:include href="FileB.xml" xpointer="xpointer(//NodeB)" /> But this doesn't give me the flexibility I need. Any ideas? Thanks,...

How do I create a new attribute that adds 2 fields Y+Y=YY
How do I create a new attribute that adds the SUM of two other attributes. It's a simple Y+Y=YY equation.. Nothing fancy very simple! The attributes are both located on the saem Opp form. CRM doesn't support calculated fields in this manner. You either need to write JScript to do the math when 1 value changes or use a Pre-callout to do the calculation before the record is saved. The callout will fire when updated are done via the API's, where the JScript won't. -- Matt Parks MVP - Dynamics CRM "ConSol IT" <ConSolIT@discussions.microsoft.com> wrote in...

XML From Stored Proc
In VB.NET (Studio 2005) I need to loop thru a result set returned from a stored proc and generate XML for each row. E.g. exex procWhatever returns: custno, lname, fname, address 2, Doe, John, 123 4th St. 3, Smith, Bill, 567 8th St. 4, Grant, Terry, 333 Wherever St. For each on of those rows I need to generate (string): <Customer> <custno>2</custno> <lname>Doe</lname> <fname>John</fname> <address>123 4th st.</address> </customer> .... Any advice, tutorials, etc. would be greatly appreciated. Thank you very much. What dat...

Generating Excel XML with embedded char(10)s
I have a script that generates an Excel file in XML. Everything is working wonderfully except for one column where I want to embed line feeds in the cells. It appears that the characters are there because when I view the XML file in a text editor, the contents of those cells are on separate lines but when I view the file in Excel, the line feed character seems to be replaced with a single space. So, for instance, I have: <Row> <Cell ss:StyleID="Default"><Data ss:Type="String">ABC Corp</Data></ Cell> <Cell ss:StyleID="Default">...