C#XML反序列化错误(2,2)

时间:2011-04-20 09:17:36

标签: c# xml xml-deserialization

学校给了我一个XML文档,我必须在屏幕上显示信息。据我所知,Xml反序列化将是最简单/最好的解决方案。

到目前为止,我有这个:

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);
}

这就是XML文档的样子:

<?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>

两种方法都抛出相同的异常:

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

如何正确反序列化上面的xml?任何样品都会有所帮助!

2 个答案:

答案 0 :(得分:2)

问题很可能是您未将正确的命名空间指定为Project类的属性。

您可以告诉XmlSerializer在反序列化期间忽略名称空间(检查this answer)。

或者,您可以使用XmlTypeAttribute

设置适当的命名空间
[XmlType(Namespace = "http://www.pulse.nl/DynamicsAX/2009/DataSets")]
public class Project 
{
   ...
}

答案 1 :(得分:1)

尝试在default namespace的构造函数中为XML文档指定XmlSerializer

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

相关资源: