反序列化 XML 个具有不同 XmlRoot 元素名称的文件
De-serialize XML files with varying XmlRoot element names
我有大量 XML 个文件需要执行反序列化。这些文件具有不同的根名称(超过 250 个)。在访问 XML class 以检索我的数据之前,我试图通过 XmlSerializer 传递根属性名称。这是我所拥有的,但我仍然收到一个错误,指出根名称是预期的,尽管 XmlElement class 正在将属性传递给 XmlSerializer class.
用于检索文件的方法:
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 classes 文件:
[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()
总是 return System.Xml.XmlElement
,这不是你想要的。
我有大量 XML 个文件需要执行反序列化。这些文件具有不同的根名称(超过 250 个)。在访问 XML class 以检索我的数据之前,我试图通过 XmlSerializer 传递根属性名称。这是我所拥有的,但我仍然收到一个错误,指出根名称是预期的,尽管 XmlElement class 正在将属性传递给 XmlSerializer class.
用于检索文件的方法:
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 classes 文件:
[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()
总是 return System.Xml.XmlElement
,这不是你想要的。