c# - 反序列化具有不同 XmlRoot 元素名称的 XML 文件

标签 c# xml xml-serialization

我有大量 XML 文件需要对其执行反序列化。这些文件具有不同的根名称(超过 250 个)。在访问 XML 类以检索我的数据之前,我试图通过 XmlSerializer 传递根属性名称。这是我所拥有的,但我仍然收到一个错误,指出根名称是预期的,尽管 XmlElement 类正在将属性传递给 XmlSerializer 类。

用于检索文件的方法:

string strXmlDoc = path;
XmlDocument objXmlDoc = new XmlDocument();
objXmlDoc.Load(strXmlDoc);
XmlElement objRootElem = objXmlDoc.DocumentElement;

XmlSerializer xmlSerial = new XmlSerializer(typeof(XMLFile), new XmlRootAttribute(objRootElem.ToString()));
StreamReader sr = new StreamReader(path);
XMLFile entity = xmlSerial.Deserialize(sr) as XMLFile;

XML 类文件:

[Serializable]
//[XmlRoot("randomname")] Removed this line since I'm getting the XmlRoot attribute in the XmlSerializer line.
public class XMLFile
{
    [System.Xml.Serialization.XmlElement("RECORD")]
    public RECORD RECORD { get; set; }
}

[Serializable]
public class RECORD
{
    [XmlElement("BK01")]
    public Record Bk01 { get; set; }

    [XmlElement("BK02")]
    public Record Bk02 { get; set; }
}

[Serializable]
public class Record
{
    [XmlAttribute("Value")]
    public string Value { get; set; }
}

最佳答案

改变这个:

XmlSerializer xmlSerial = 
    new XmlSerializer(typeof(XMLFile), new XmlRootAttribute(objRootElem.ToString()));

为此:

XmlSerializer xmlSerial = 
    new XmlSerializer(typeof(XMLFile), new XmlRootAttribute(objRootElem.Name));
                                                                        ^^^

XmlElement.ToString() 将始终返回 System.Xml.XmlElement,这不是您想要的。

关于c# - 反序列化具有不同 XmlRoot 元素名称的 XML 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57579617/

相关文章:

c# - WPF Dispatcher Invoke 返回值始终为 null

c# - MVC 4 中的自定义成员提供程序

xml - 在线性布局中居中按钮

c# - LINQ to XML 使用 idref 连接

c# - 如何在 C# 中仅从 DateTime 序列化 Xml Date

c# - 来自 Windows 窗体的 WPF 最佳实践

c# - 在 Linq 中按 DayOfWeek 分组

c# - 以编程方式在 c# 中添加 [XmlIgnore] 属性以进行序列化

c# - 生成 XML 文档时出错。类型 Job 不是预期的

.net - 有没有办法让 xsd.exe 生成范围为 "internal"的类?