[英]Deserialize XML Elements Return NULL
I am trying to deserialize an XML file.我正在尝试反序列化 XML 文件。 However, I only want two elements from the file.
但是,我只想要文件中的两个元素。 Here's the basic markup:
这是基本标记:
<Stuff>
<Details>
<Comment>I want whats in here.</Comment>
<LogLevel>And here too.</LogLevel>
</Details>
<Stuff>
To deserialize I'm doing the following:要反序列化,我正在执行以下操作:
XmlSerializer deserializer;
FileStream stream = new FileStream(CONFIG_PATH, FileMode.Open);
XmlReader reader = new XmlTextReader(stream);
XmlRootAttribute xRoot = new XmlRootAttribute();
xRoot.ElementName = "Stuff";
xRoot.IsNullable = true;
// Details configuration area.
Utilities.Details d = new Utilities.Details();
deserializer = new XmlSerializer((typeof(Details)), xRoot);
d = (Details)deserializer.Deserialize(reader);
System.Windows.MessageBox.Show(d.Comment);
And finally the class that holds the objects:最后是包含对象的 class :
/// <summary>
/// Configuration details.
/// </summary>
[Serializable()]
[XmlRoot(ElementName = "Details", IsNullable = true)]
public sealed class Details
{
public Details()
{
}
[XmlElement("Comment")]
public string Comment { get; set; }
[XmlElement("LogLevel")]
public string LogLevel { get; set; }
}
However d.Comment and d.LogLevel continue to return null no matter what I do.然而 d.Comment 和 d.LogLevel 继续返回 null 无论我做什么。 Any ideas?
有任何想法吗?
With that setup, it expects通过该设置,它期望
<Stuff>
<Comment>....
<LogLevel>...
...
To handle two levels in the XML you will need an object model that matches.要处理 XML 中的两个级别,您将需要匹配的 object model。 Rather than messing with the XmlRootAttribute at runtime, write a type Stuff that has a Details instance in a property called Details.
与其在运行时弄乱 XmlRootAttribute,不如编写一个类型 Stuff,它在名为 Details 的属性中具有一个 Details 实例。 Then create the serializer to expect a Stuff instance:
然后创建序列化程序以期望 Stuff 实例:
public class Stuff {
public Details Details {get;set;}
}
An alternative approach would be to use a sub-reader over the input, but that is harder.另一种方法是在输入上使用子阅读器,但这更难。
I ran into a lot of similar issues when I was attempting to use XmlSerializer and FileStreams.我在尝试使用 XmlSerializer 和 FileStreams 时遇到了很多类似的问题。
I would suggest changing this to Linq to XML.我建议将其更改为 Linq 到 XML。 I found it to be a lot easier and faster to learn.
我发现它更容易和更快地学习。
Here is a great Video by Mike Taulty这是 Mike Taulty 的精彩视频
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.