gpt4 book ai didi

c# - 未知属性 xsi :type in XmlSerializer

转载 作者:行者123 更新时间:2023-11-30 18:09:02 25 4
gpt4 key购买 nike

我正在学习 XML 序列化并遇到一个问题,我有两个类(class)

[System.Xml.Serialization.XmlInclude(typeof(SubClass))]
public class BaseClass
{

}

public class SubClass : BaseClass
{
}

我正在尝试将一个 SubClass 对象序列化为 XML 文件,我使用的是代码

XmlSerializer xs = new XmlSerializer(typeof(Base));
xs.Serialize(fs, SubClassObject);

我注意到序列化成功了,但是 XML 文件有点像

<?xml version="1.0"?>
<BaseClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xsi:type="SubClass">
...
</Employee>

如果我用

XmlSerializer xs = new XmlSerializer(typeof(Base));
SubClassObject = xs.Deserialize(fs) as SubClass;

我注意到它会提示 xsi:type is unknown attribute(我注册了一个事件),尽管 XML 中嵌入的所有信息都已成功解析并且 SubClassObject 中的成员已正确恢复。

有人知道为什么在解析 xsi:type 时出错以及我做错了什么吗?

谢谢

最佳答案

这是我写的程序

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;

namespace XmlIncludeExample
{
[XmlInclude(typeof(DerivedClass))]
public class BaseClass
{
public string ClassName = "Base Class";
}

public class DerivedClass : BaseClass
{
public string InheritedName = "Derived Class";
}

class Program
{
static void Main(string[] args)
{
string fileName = "Test.xml";
string fileFullPath = Path.Combine(Path.GetTempPath(), fileName);

try
{
DerivedClass dc = new DerivedClass();

using (FileStream fs = new FileStream(fileFullPath, FileMode.CreateNew))
{
XmlSerializer xs = new XmlSerializer(typeof(BaseClass));
xs.Serialize(fs, dc);
}

using (FileStream fs = new FileStream(fileFullPath, FileMode.Open))
{
XmlSerializer xs = new XmlSerializer(typeof(BaseClass));
DerivedClass dc2 = xs.Deserialize(fs) as DerivedClass;
}
}
finally
{
if (File.Exists(fileFullPath))
{
File.Delete(fileFullPath);
}
}
}
}
}

这产生了以下 xml

<?xml version="1.0" ?> 
- <BaseClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xsi:type="DerivedClass">
<ClassName>Base Class</ClassName>
<InheritedName>Derived Class</InheritedName>
</BaseClass>

成功了

关于c# - 未知属性 xsi :type in XmlSerializer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2748132/

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