Solved

How to create XDocument from XmlWriter and DataContractSerializer without all the extra attributes

Posted on 2011-09-06
2
1,262 Views
Last Modified: 2013-12-17
Suppose I have a Thing class:

[DataContract]
    public class Thing
    {
        [DataMember]
        public string Name;

        [DataMember]
        public List<KeyValuePair<string, object>> attributes = new List<KeyValuePair<string,object>>();

        [DataMember]
        public List<KeyValuePair<string, object>> Attributes
        {
            get { return attributes; }
            set { attributes = value; }
        }
    }

Open in new window


And then suppose I serialize an object of the Thing class into a XDocument like this:

using (StringWriter stringWriter = new StringWriter())
            {
                using (XmlWriter xmlWriter = XmlWriter.Create(stringWriter))
                {
                    var serializer = new DataContractSerializer(typeof(Thing));                    
                    serializer.WriteObject(xmlWriter, someThing);             
                    xmlWriter.Flush();    
                    string sss = stringWriter.ToString();
                    XDocument xDoc2 = XDocument.Parse(sss);
                }
            }

Open in new window


All I want to get is something like this:

<Thing>
   <keyValuePair>
      <key>key1</key>
      <value>val1</value>
   </keyValuePair>
      <key>key2</key>
      <value>val2</value>
   </keyValuePair>
</Thing>

Open in new window


Instead, what I get is this:

<Thing xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/WCFSession">
  <Attributes xmlns:d2p1="http://schemas.datacontract.org/2004/07/System.Collections.Generic">
    <d2p1:KeyValuePairOfstringanyType>
      <d2p1:Key>key1</d2p1:Key>
      <d2p1:Value xmlns:d4p1="http://www.w3.org/2001/XMLSchema" i:type="d4p1:string">obj1</d2p1:Value>
    </d2p1:KeyValuePairOfstringanyType>
    <d2p1:KeyValuePairOfstringanyType>
      <d2p1:Key>key2</d2p1:Key>
      <d2p1:Value xmlns:d4p1="http://www.w3.org/2001/XMLSchema" i:type="d4p1:string">obj2</d2p1:Value>
    </d2p1:KeyValuePairOfstringanyType>
  </Attributes>
  <Name>myName</Name>
  <attributes xmlns:d2p1="http://schemas.datacontract.org/2004/07/System.Collections.Generic">
    <d2p1:KeyValuePairOfstringanyType>
      <d2p1:Key>key1</d2p1:Key>
      <d2p1:Value xmlns:d4p1="http://www.w3.org/2001/XMLSchema" i:type="d4p1:string">obj1</d2p1:Value>
    </d2p1:KeyValuePairOfstringanyType>
    <d2p1:KeyValuePairOfstringanyType>
      <d2p1:Key>key2</d2p1:Key>
      <d2p1:Value xmlns:d4p1="http://www.w3.org/2001/XMLSchema" i:type="d4p1:string">obj2</d2p1:Value>
    </d2p1:KeyValuePairOfstringanyType>
  </attributes>
</Thing>

Is there a way to use the XmlWriter with the DataContractSerializer to get the simple result I showed above instead all the extra attributes and schema information?



0
Comment
Question by:XTO
2 Comments
 
LVL 75

Assisted Solution

by:käµfm³d 👽
käµfm³d   👽 earned 50 total points
ID: 36491768
What if you used a plain XmlSerializer (under the System.Xml.Serialization namespace)?
0
 
LVL 9

Accepted Solution

by:
Grant Spiteri earned 200 total points
ID: 36499844
Here are 2 Generic xml serializer methods

 
/// <summary>
        /// Serializes from string to specified generic type
        /// </summary>
        /// <typeparam name="T">The type passed in</typeparam>
        /// <param name="typeToSerializeTo">The type of object you wish to serialize to, very handy when passing in IObjects as apose to concrete types.</param>
        /// <param name="objectToDeserialize">The object to deserialize.</param>
        /// <returns></returns>
        public static T SerializeFromString<T>(T typeToSerializeTo, string objectToDeserialize)
        {
            using (var sr = new StringReader(objectToDeserialize))
            using (var reader = new XmlTextReader(sr))
            {
                var xs = new XmlSerializer(typeToSerializeTo.GetType());
                return (T) xs.Deserialize(reader);
            }
        }

        public static T DeserializeValidatedXml<T>(string data)
        {
            using (var sr = new StringReader(data))
            using (var reader = new XmlTextReader(sr))
            {
                var xs = new XmlSerializer(typeof (T));
                return (T) xs.Deserialize(reader);
            }
        }

Open in new window

0

Featured Post

Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This document covers how to connect to SQL Server and browse its contents.  It is meant for those new to Visual Studio and/or working with Microsoft SQL Server.  It is not a guide to building SQL Server database connections in your code.  This is mo…
This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
Although Jacob Bernoulli (1654-1705) has been credited as the creator of "Binomial Distribution Table", Gottfried Leibniz (1646-1716) did his dissertation on the subject in 1666; Leibniz you may recall is the co-inventor of "Calculus" and beat Isaac…
Nobody understands Phishing better than an anti-spam company. That’s why we are providing Phishing Awareness Training to our customers. According to a report by Verizon, only 3% of targeted users report malicious emails to management. With compan…

821 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question