gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 02:32:15 26 4
gpt4 key购买 nike

学校给了我一个 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?任何示例都会有所帮助!

最佳答案

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

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

或者,您可以使用 XmlTypeAttribute 设置适当的命名空间:

[XmlType(Namespace = "http://www.pulse.nl/DynamicsAX/2009/DataSets")]
public class Project
{
...
}

关于C# XML反序列化错误(2,2),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5728062/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com