开发者

C# XML Deserializing Error (2,2)

开发者 https://www.devze.com 2023-02-28 02:12 出处:网络
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.

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</StartDa开发者_C百科te>
        <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!


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 
{
   ...
}


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:

  • XmlSerializer Constructor
  • XML namespace
0

精彩评论

暂无评论...
验证码 换一张
取 消