c# – 在使用XmlSerializer反序列化XML时保留仅空白元素内容
发布时间:2020-12-15 04:34:34 所属栏目:百科 来源:网络整理
导读:我有一个InputConfig类,它包含一个List IncludeExcludeRule: public class InputConfig{ // The rest of the class omitted private ListIncludeExcludeRule includeExcludeRules; public ListIncludeExcludeRule IncludeExcludeRules { get { return inclu
我有一个InputConfig类,它包含一个List< IncludeExcludeRule>:
public class InputConfig { // The rest of the class omitted private List<IncludeExcludeRule> includeExcludeRules; public List<IncludeExcludeRule> IncludeExcludeRules { get { return includeExcludeRules; } set { includeExcludeRules = value; } } } public class IncludeExcludeRule { // Other members omitted private int idx; private string function; public int Idx { get { return idx; } set { idx = value; } } public string Function { get { return function; } set { function = value; } } } 使用…… FileStream fs = new FileStream(path,FileMode.Create); XmlSerializer xmlSerializer = new XmlSerializer(typeof(InputConfig)); xmlSerializer.Serialize(fs,this); fs.Close(); ……而且…… StreamReader sr = new StreamReader(path); XmlSerializer reader = new XmlSerializer(typeof(InputConfig)); InputConfig inputConfig = (InputConfig)reader.Deserialize(sr); 它就像一个冠军!简单的东西,除了我需要在反序列化时保留成员函数中的空格.生成的XML文件表明序列化时保留了空格,但在反序列化时丢失了. <IncludeExcludeRules> <IncludeExcludeRule> <Idx>17</Idx> <Name>LIEN</Name> <Operation>E =</Operation> <Function> </Function> </IncludeExcludeRule> </IncludeExcludeRules> MSDN documentation for XmlAttributeAttribute似乎在标题备注下解决了这个问题,但我不明白如何使用它.它提供了这个例子: // Set this to 'default' or 'preserve'. [XmlAttribute("space",Namespace = "http://www.w3.org/XML/1998/namespace")] public string Space 咦?设置“默认”或“保留”的内容?我确定我很接近,但这只是没有意义.我必须认为只有一行XmlAttribute在成员之前插入类中以在反序列化时保留空格. 在这里和其他地方有许多类似问题的实例,但它们似乎都涉及使用XmlReader和XmlDocument,或者涉及单个节点等.我想避免这种深度. 解决方法
要在XML反序列化期间保留所有空格,只需创建并使用XmlReader:
StreamReader sr = new StreamReader(path); XmlReader xr = XmlReader.Create(sr); XmlSerializer reader = new XmlSerializer(typeof(InputConfig)); InputConfig inputConfig = (InputConfig)reader.Deserialize(xr); 与XmlSerializer.Deserialize(XmlReader)不同, (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |