我有大量 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/