Solved

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

Posted on 2011-09-06
2
1,242 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 74

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

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

Join & Write a Comment

For those of you who don't follow the news, or just happen to live under rocks, Microsoft Research released a beta SDK (http://www.microsoft.com/en-us/download/details.aspx?id=27876) for the Xbox 360 Kinect. If you don't know what a Kinect is (http:…
More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.
This video shows how to remove a single email address from the Outlook 2010 Auto Suggestion memory. NOTE: For Outlook 2016 and 2013 perform the exact same steps. Open a new email: Click the New email button in Outlook. Start typing the address: …

706 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

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now