Solved

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

Posted on 2011-09-06
2
1,277 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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

PeopleSoft Has Never Been Easier

PeopleSoft Adoption Made Smooth & Simple!

On-The-Job Training Is made Intuitive & Easy With WalkMe's On-Screen Guidance Tool.  Claim Your Free WalkMe Account Now

Question has a verified solution.

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

Introduction Hi all and welcome to my first article on Experts Exchange. A while ago, someone asked me if i could do some tutorials on object oriented programming. I decided to do them on C#. Now you may ask me, why's that? Well, one of the re…
Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…
Attackers love to prey on accounts that have privileges. Reducing privileged accounts and protecting privileged accounts therefore is paramount. Users, groups, and service accounts need to be protected to help protect the entire Active Directory …

710 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