如何使用 XmlSerializer 类反序列化这个简单的 xml 配置? [英] How do I deserialize this simple xml config with the XmlSerializer class?
本文介绍了如何使用 XmlSerializer 类反序列化这个简单的 xml 配置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下 xml 我想反序列化为一个类
I have the following xml I'd like to deserialize into a class
<?xml version="1.0" encoding="utf-8" ?>
<root>
<element1>String1</element1>
<element2>String2</element2>
</root>
我正在尝试将其序列化为以下类:
I am trying to serialize it into the following class:
[XmlRoot("root")]
public class root
{
[XmlElement("element1")]
internal string element1 { get; set; }
[XmlElement("element2")]
internal string element2 { get; set; }
}
当我尝试使用以下代码反序列化它时,配置对象被实例化,但字符串为空.
When I try deserializing it using the following code, the config object is instantiated, but the strings are null.
using (TextReader reader = new StreamReader(configFile))
{
XmlSerializer serializer = new XmlSerializer(typeof(root));
this.config = (root)serializer.Deserialize(reader);
}
我已经尝试使用 xsd.exe 创建一个 xsd,然后基于它创建一个类,但是该工具产生的混乱太多了.我想我已经接近这里了.我错过了什么?
I've tried using xsd.exe to create an xsd, and then create a class based off of that, but there is too much clutter generated by that tool. I think I'm close here. What am I missing?
推荐答案
你不能序列化/反序列化内部属性 - 它们必须是公开的.
You can't serialise/deserialise internal properties - They have to be public.
这篇关于如何使用 XmlSerializer 类反序列化这个简单的 xml 配置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文