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

Similar Articles

[PageSpeed] 9

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:

Creating XML element from XPath
Hi, Is it possible to automatically create an XML element given an XPath query? For example I have the following XML doc: <topic> <title>Hi this is the title</title> <description>This is a simple desc</description> </topic> Now say I have an XPath query '/topic/age' which will return a null node if I run it against the above XML doc. Now is there an easy way to automatically create the age node if it doesn't exist? Or do I need to do manual parsing and create the node manually? For the above example probably you'll think that ...

Lookup on custom entity without relationship
First,I will show existing out-of-the-box sample in MS CRM3: Address entity is in relation to account M:1.When I stay on order entity and press on lookup addresses I get result filtered only for account selected in order. Order there is no relation to address entity. My problem: I created new CustomEntity1 with relationship to Account 1:M. Now, I want to add to Order field from CustomEntity1, filtered only by currently selected in order Account.If I add relationship CustomEntity1->Order, I think, I will get in lookup all CustomEntity1 records without filter by order account. Please help ASA...

New to xml
I'm trying to write my xsl to display an unordered list fromt the xml file where location is equal to top: <siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0" > <siteMapNode url="~/index.aspx" title="Home" location="top"> <siteMapNode url="~/about_us/index.aspx" title="About Us" location="top" > <siteMapNode url="~/about_us/mediaroom.aspx" title="Media Room" /> <siteMapNode url="~/about_us/awards.aspx" title="Awards" /> <siteMapNo...

controlling spam with MSExchange.UceContentFilter.xml
Hi I need to know if there is a way of using a wild card word inconjunction with the MSExchange.UceContentFilter.xml. I will try to explain, recently our ISP who provide our first line spam filtering changed their methods of controlling spam and since this change we are getting alot more spam into our exchange systems. They delete obvious spam but the ones they are a little unsure about they now send it out and adjust the subject to include the word spam I now this sounds daft but just go along with it. So we are getting alot of spam with the different subjects all prefixed with {s...

Parse XML into Collection
I'm a newbie so please bear with me... I'm looking to parse XML into a Collection so that I can pass that collection around to functions to extract data from it easily. I'm hoping there is code already to parse std XML files into a Collection? All I've found is code where the XML structure is already known... I need to code to work no matter what the structure... it would "figure out" what nodes are parents/children and such then place them into a Collection appropriately. Any help is appreciated! An XmlDocument already defines a hierarchy of collections when it p...

How do I write a response to a request from an xml data island?
I need to know the code I must write to respond xml to a data island as a result from a src request from the data island. Thanks so much Assuming the data island has a src attribute like: "getXML.asp", this ASP page would do it: <%@ language="JScript"%> <% var xmlDoc = new ActiveXObject("MSXML2.DomDocument"); xmlDoc.loadXML("<root>Some XML</root>"); Response.ContentType="text/xml"; xmlDoc.save(Response); %> Regards, Mike Sharp "Nicole Schenk" wrote: > I need to know the code I must write to respond x...

DataSet and xml data without schema
Hi, How can I read data into an DataSet from an xml file that doesn't contain any schema references. The dataset is wysiwyg-created in VisualStudio. I've already tried the ...DataSet.ReadXml() method but that doesn't fill my dataset with the data from the file and also doesn't raise any errors. How can I convince the ...DataSet to read data from the unschematized xml-file? Erik ...

Exchange 2003 Recoevery without Systemstate
My Exchange 2003 Raid-5 Menber Server crashes, the only Backup from this System was the Full Backup of the Exchange Informations Store, no systemstate Backup available. I set up the new Server (2003 plus Exch2003) and tried to restore the Exchange Database with ntbackup. This Restore fails with the 9635 Event. Any ideas how to restore my 6 GB Database. If you use RSG or you trying to restore to the original location, you should use exactly the same names and locations for the SG and Store, if not otherwise mentioned. also, On the Database tab of the Mailbox Store Properties dialog box for...

Serialization Problem
Hi, I am trying to use the following code to make xml serialization to a file. The following error is being given: "An unhandled exception of type 'System.InvalidOperationException' occurred in system.xml.dll Additional information: There was an error generating the XML document." The problem should be due to inheritance. Can someone help me solve the problem out. Thanks in Advance ICommunicationTuple ict = new MessageQueueCommunication("test"); XmlSerializer ser = new XmlSerializer(typeof(ICommunicationTuple)); StreamWriter writer = new StreamWriter("c...

Can not Load XML
Hi I am trying to load the XML document from a file like XmlDocument requestDoc = new XmlDocument(); requestDoc.Load( strFileName ); I am getting Error '&#9792;', hexadecimal value 0x0C, is an invalid character. Line 1940, position 1. I can load the same file using IE 6.0 with out any errors I am using Visual Studio .Net 1.1(2003) Any Clues ???? Thanks Kiran Kiran, 0x0C is not a legal character in any XML document (regardless if IE does display it). The spec explicitly spells out which characters may occur in a legal document [0]. You can find more information on thi...

XML newbie: How to add/replace an attribute
Hi all, Whenever I need to deal with XML I kind of stumble around in the XML namespace until I find the class that seems to do what I'm trying to do. This time around, I've been trying to find a reasonably straightforward way to do something that should be very simple, and I've gotten to the point where I need to ask for help. I have a bunch of files that contain XML looks like this: <?xml version="1.0" encoding="utf-8"?> <manifest version="1" exceptions="*.doc"> <file>.\abc.txt</file> <file>.\def.txt&...

How to run client-side scripts without picklist OnChange event?
Is there a way to run a client side script from a CRM form other than using the picklist OnChange event? I need to do some simple data validation when a text boxt changes or when a product is selected for a quote. In this version, the picklist is the only supported way of accomplishing this. However, if you are good with XML, you can hack javascript into other fields. - First, make sure you have an OnChange defiend for a picklist field. - Then export the customizations to an XML file. - Now edit the XML file and find where the OnChange event you added is. Add a similar node to anot...

how to find nodes at xml file without complete load the xml file
how to find nodes at xml file without complete load the xml file since the file is very big!! joe wrote: > how to find nodes at xml file without complete load the xml file > since the file is very big!! You can read through the XML document with an Xml(Text)Reader, that is forward only pull parsing where your code only pulls in the current node. The documentation is here <http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfSystemXmlXmlTextReaderClassTopic.asp> for .NET 1.x and here <http://msdn2.microsoft.com/en-us/library/system.xml.xmlreader(...

List of available serial ports
How can I get a list of available serial ports from Windows? I need to have my user select from the list. Ron H. ----------------- www.Newsgroup-Binaries.com - *Completion*Retention*Speed* Access your favorite newsgroups from home or on the road ----------------- >How can I get a list of available serial ports from Windows? I need to have >my user select from the list. You could try this: http://www.codeproject.com/KB/system/enumports.aspx Dave Serial port list is in registry HKEY_LOCAL_MACHINE\\DEVICEMAP\\SERIALCOMM For Win CE machines HKEY_LOCAL_MACHINE\\Drivers\\Active ...

How to create xml elements with special chars
Hi, newbie that i am in .Net, i'm trying to add "D/T" as a new element in C# : XmlElement elemAttr = (XmlElement)m_xmlDoc.AppendChild(m_xmlDoc.CreateElement("D/T" ) ); but the framework throws an XmlException ... how do i overcome this ? do i have to parse the string for special chars myself ? please advise, thanks , nim_co. *** Sent via Developersdex http://www.developersdex.com *** Don't just participate in USENET...get rewarded for it! I don't think that you can. The XML standard limits the characters you can use (http://www.w3.org/TR/xml11/#dt-elem...

Saving without VBA code
I have a workbook that has some VBA code in the ThisWorkbook module to define a toolbar button. This button uses VBA code in another module to save a set of ranges to a new spreadsheet file. I accomplish this by creating a new workbook, copying each range (each is on a separate worksheet), then saving the new workbook with a new name. Unfortunately, the VBA code in ThisWorkbook is also copied to the new workbook, so when the new spreadsheet file is opened, it also has the toolbar button. Is there any way to do this without also copying the VBA code from ThisWorkbook? Or, is there a way to remo...

Excel-Can't close 1 open Workbook without closing other open Workb
This concerns Excel 10(?). I have Office XP, but it is Office 10 in my explorer files. Problem: I have a few opened Workbooks that I'm working on. When I close one Workbook, it closes all open Workbooks at once. How do I separate them and stop all these from closing at once? Has something changed to the template--"Book1.xls"? If so, how do I correct that? Are you clicking the X in the most upper-right corner? If so, that's closing Excel as a whole, regardless of how many worksheets are open. To close one, click on the X that is below the main one in the upper right ...

Object to use for sending URL / retrieving XML
How do I get XML results from a URL into a set of variables (or controls on a form, or anywhere else I can use them within Access)? I need to build an interface to the Washington State tax code URL interface as a small part of a much larger application that has been running for several years. Their site accepts address-related arguments as part of the URL, then returns XML results. Here is the URL, using their example address (probably their office), so there is nothing confidential here: http://dor.wa.gov/AddressRates.aspx?output=xml&addr=6500 Linderson way&city=&am...

Can I create a report from this without a macro?
(XL2007) My data is presented in 5-row groups. Cols A, B, and C have my identifiers; col AU has a text value I need to include. Headers in row 9; cells in cols A, B and C are merged in groups of five (A10:A14 merged, A15:19 merged, etc, and same for B and C); in the Name Box, though, data in the A10:A14 merged group shows up as A10. Col A is the major group, col B is the sub-group, and col C is the ID number of the sub-group. What I would like is something like a pivot table. I tried that, though, and XL told me I didn't have a valid range, or valid headers, or something like that. ...

How I import data without truncating zero in the beginning
I am importing data from text file to access database but it is truncating all the zeros if they come in the starting.... please help me to resolve this problem as there is a field name telephone number and I need zero in the starting to distinguish between local and international calls. Remplace them by "+" (normaly it's the same) "Mohsin Habib" <MohsinHabib@discussions.microsoft.com> a écrit dans le message de news:8B32A18C-E88B-4259-8CAE-332EB821883C@microsoft.com... >I am importing data from text file to access database but it is truncating > ...

decimal attribute
I'm trying to create new attrubute, but I don't see decimal type in dropdown list when I choose type. How can I create decimal attribute? Thyank you. -- Alex Alex Use a FLOAT data type for numbers with decimals. Dave "Alex" <Alex@discussions.microsoft.com> wrote in message news:7222E339-2322-4837-A209-2EF4C4B8695E@microsoft.com... > I'm trying to create new attrubute, but I don't see decimal type in > dropdown > list when I choose type. How can I create decimal attribute? > > Thyank you. > > -- > Alex Yes, I can use float,...

Converting dataset xml into adodb.recordset???
Hi, I have a need to conver the xml produced by a .net dataset (with a single table) into an adodb.recordset. The adodb.recordset doesn't understand the xml that the dataset.GetXml method produces. Can someone point me in the right direction? Thanks ... Ed Hi, see the code download for Dino Esposito's "Applied XML Programming for Microsoft .NET" http://www.microsoft.com/MSPress/books/6235.asp . In chapter 4 there is written as an example an XmlRecordsetWriter class (custom XML writer) which is capable to write ADO recordset compliant XML. It has WriteRecordset meth...

extracting a XML segment (element)
Hello, I need to extract an element from a xml document something like this <myXml> <Header> <Name/> <LastName/> <Age/> </Head> <Body> <Properties> <Address/> <Location/> <Country> </Properties> </Body> </myXml> I need to extract from my Stream the <Properties> element (and sub elements) located inside the Body element. How can I do that? Thanks a lot again! AA I forgot to mention that the element <P...

What is the Best XML API for .NET 3.5?
I’m starting a new project which will dynamically generate (user will have to pick and choose data, then generate the XML dynamically) RDLC for Reporting. My approach was to use LINQ to XML for the API. My question is what is the best API to use? Performance is no concern, most critical factor is that the code be easy to maintain easy to dynamically generate the mark-up for the RDLC. Note: We are all ready using LINQ to XML in the main application. This is for the reprinting module of the application. -- Alexander L. Wykel AW Software Works Alexander Wykel wrote: > I’m start...

Excel file grew without explanation to 12mb?!
I have a very simple excel file - litterally just a column of numbers to add (maybe 20 numbers), on 4 worksheets, and a few titles (nothing fancy). There are three sum functions and that is it. No graphics, no macros, no links, no advanced functions. For some reason the file is 12mb so it can't be e-mailed. Any ideas on what happened, how to trouble-shoot it, or what to do to get it to a reasonable size? There is no reason I can think of for this file to be larger than 100k. Warren, Try going to View\Page Break Preview. Drag the blue dividers into place for the sheet of data yo...