C# XML 反序列化错误 (2,2)
学校给了我一个 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?任何样品都会有帮助!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
最有可能的问题是您没有指定正确的命名空间作为
Project
类的属性。您可以告诉 XmlSerializer 在反序列化期间忽略命名空间(检查 此回答)。
或者,您可以使用
XmlTypeAttribute
设置适当的命名空间: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
:尝试在 默认命名空间 http://msdn.microsoft.com/en-us/library/swxzdhc0.aspx" rel="nofollow">XmlSerializer:
相关资源:
Try specifying the default namespace for the XML document in the constructor of the XmlSerializer:
Related resources: