Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

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

Posted on 2011-09-06
2
Medium Priority
?
1,306 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 200 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 800 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

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

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…
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
How to fix incompatible JVM issue while installing Eclipse While installing Eclipse in windows, got one error like above and unable to proceed with the installation. This video describes how to successfully install Eclipse. How to solve incompa…
We’ve all felt that sense of false security before—locking down external access to a database or component and feeling like we’ve done all we need to do to secure company data. But that feeling is fleeting. Attacks these days can happen in many w…

722 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