3

School gave me an XML document, and I have to display the information on a screen. As far as I know, Xml Deserialization would be the easiest/nicest solution.

I have this so far:

public static List<Project> ProjectListDeserialize(string path)
{
    XmlSerializer serializer = new XmlSerializer(typeof(List<Project>));
    Stream filestream = new FileStream(path, FileMode.Open);
    return (List<Project>)serializer.Deserialize(filestream);
}

public static Projects ProjectsDeserialize(string path)
{
    XmlSerializer serializer = new XmlSerializer(typeof(Projects));
    Stream filestream = new FileStream(path, FileMode.Open);
    return (Projects)serializer.Deserialize(filestream);
}

And this is how the XML document looks like:

<?xml version="1.0" encoding="utf-16" ?>    
<Projects xmlns="http://www.pulse.nl/DynamicsAX/2009/DataSets" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <Project ID ="1000.0001" CustomerID="1000">
        <Name>Project data key performance indicators</Name>
        <Status>WorkInProgress</Status>
        <StartDate>2011-01-01</StartDate>
        <ExpectedCompletionDate>2011-08-01</ExpectedCompletionDate>
        <CompletionDate xsi:nil="true" />
    </Project>
    <Project ID ="1000.0008" CustomerID="1000" ParentID="1000.0001">
        <Name>Implementation</Name>
        <Status>WaitListed</Status>
        <StartDate>2011-06-01</StartDate>
        <ExpectedCompletionDate>2011-08-01</ExpectedCompletionDate>
        <CompletionDate xsi:nil="true" />
    </Project>
</Projects>

Both methods are throwing the same exception:

<Projects xmlns='http://www.pulse.nl/DynamicsAX/2009/DataSets was not expected

How can I correctly deserialize the above xml? Any samples would be helpful!

Ryan Gates
  • 4,501
  • 6
  • 50
  • 90
Jordy Langen
  • 3,591
  • 4
  • 23
  • 32
  • did you define namespaces in project/s class definitions? – mmix Apr 20 '11 at 09:21
  • You should remove the xmlns from the Projects element. or write a custom serializer. or use the xsd tool in the .NET SDK to generate C# classes that are compatible with that Xml format – Glenn Ferrie Jan 14 '14 at 14:40

2 Answers2

2

Most likely the problem is that you didn't specify the right namespace as an attribute for your Project class.

You can tell the XmlSerializer to ignore the namespaces during deserialization (check this answer).

Alternatively, you can set the appropriate namespace using the XmlTypeAttribute:

[XmlType(Namespace = "http://www.pulse.nl/DynamicsAX/2009/DataSets")]
public class Project 
{
   ...
}
Community
  • 1
  • 1
vgru
  • 49,838
  • 16
  • 120
  • 201
1

Try specifying the default namespace for the XML document in the constructor of the XmlSerializer:

var serializer = new XmlSerializer(typeof(Projects), "http://www.pulse.nl/DynamicsAX/2009/DataSets");

Related resources:

Enrico Campidoglio
  • 56,676
  • 12
  • 126
  • 154