Davita
Davita

Reputation: 9114

How to deserialize this xml?

I have the following xml I want to deserialize into object. I'm using C#.

    <?xml version = '1.0' encoding = 'windows-1251'?>
    <RootElement>
      <AnotherRoot>
        <parameter name="param1">
          <value>"12"</value>
        </parameter>
        <parameter name="param2">
          <value>"John"</value>
        </parameter>
      </AnotherRoot>
    </RootElement>

Any idea?

Upvotes: 0

Views: 302

Answers (4)

Pieter Germishuys
Pieter Germishuys

Reputation: 4886

You could opt with the following

  1. Save the XML as a file
  2. Generate an XSD from the XML using either Visual Studio's XML tools or the xsd.exe from the Visual Studio Command line located in the Start -> Programs -> Visual Studio 2008/2010 -> Visual Studio Tools -> *Command Line
  3. Generate a serializable class using the save xsd.exe but now on the .xsd and with the /c argument
  4. Include the Generated code inside your solution
  5. Inside your code

    XmlSerializer serializer = new XmlSerializer(typeof(YourRootElement)); YourRootElement deserializedObject = (YourRootElement)serializer.DeSerialize(File.Open(yourXmlFileLocation);

Now you can work with it in a familiar C# object oriented way.

Upvotes: 2

Carson63000
Carson63000

Reputation: 4232

Have a read of http://www.diaryofaninja.com/blog/2010/05/07/make-your-xml-stronglytyped-because-you-can-and-its-easy for a nice overview of how to use xsd.exe to generate a schema definition from an XML file, and from there generate a class that you can deserialize into easily.

Upvotes: 0

Gideon
Gideon

Reputation: 18491

If you're using .NET 4, you could go for the dynamic route. See here for an example:
http://blogs.msdn.com/b/mcsuksoldev/archive/2010/02/04/dynamic-xml-reader-with-c-and-net-4-0.aspx

Upvotes: 2

Oded
Oded

Reputation: 498972

You need an class to deserialize it into.

What this class looks like and how it relates to your XML is something you need to decide.

Look at the DataContractSerializer and the different attributes (DataContractAttribute and DataMemberAttribute) it uses to serialize/deserialize.

Upvotes: 0

Related Questions