反序列化C#时阅读xml元素 [英] Read xml element while deserializing c#

查看:67
本文介绍了反序列化C#时阅读xml元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个xml文档,其中我对数据进行了动态序列化,如果我有新请求,则附加新数据.我序列化的对象属性是这样

I have an xml document, where i serialize data dinamically, appending new data if i have a new request. The object properties i serialize are like this

[XmlRoot("LogRecords")]
public class LogRecord
{
    public string Message { get; set; }
    public DateTime SendTime { get; set; }
    public string Sender { get; set; } 
    public string Recipient { get; set; }
}

序列化是通过这种方式完成的:

Serializing is done in this way :

var stringwriter = new StringWriter();
var serializer = new XmlSerializer(object.GetType());

serializer.Serialize(stringwriter, object);
var smsxmlStr = stringwriter.ToString();

var smsRecordDoc = new XmlDocument();
smsRecordDoc.LoadXml(smsxmlStr);

var smsElement = smsRecordDoc.DocumentElement;

var smsLogFile = new XmlDocument();
smsLogFile.Load("LogRecords.xml");

var serialize = smsLogFile.CreateElement("LogRecord");
serialize.InnerXml = smsElement.InnerXml;
smsLogFile.DocumentElement.AppendChild(serialize);

smsLogFile.Save("LogRecords.xml");

序列化时,我使用 LogFile.CreateElement("LogRecord"),而我的xml文件如下所示:

While serializing i use LogFile.CreateElement("LogRecord") and my xml file looks like this :

<LogRecords>
  <LogRecord>
    <Message>Some messagge</Message>
    <SendTime>2017-12-13T22:04:40.1109661+01:00</SendTime>
    <Sender>Sender</Sender>
    <Recipient>Name</Recipient>
  </LogRecord>
  <LogRecord>
    <Message>Some message too</Message>
    <SendTime>2017-12-13T22:05:08.5720173+01:00</SendTime>
    <Sender>sender</Sender>
    <Recipient>name</Recipient>
  </LogRecord>
</LogRecords>

当我尝试像这样反序列化

When i try to deserialize like this

 XmlSerializer deserializer = new XmlSerializer(typeof(LogRecord));
 TextReader reader = new StreamReader("LogRecords.xml");
 object obj = deserializer.Deserialize(reader);
 LogRecord records = (LogRecord)obj;
 reader.Close();

对于每个属性 Message Sender Recipient 和每个 SendTime 的随机值,我得到的都是空值,并且我知道这是因为它无法识别我在序列化时添加的XmlElement LogRecord .有什么方法可以读取此xml元素,以便我可以采用正确的属性值?

I get null value for each property Message, Sender Recipient and a random value for SendTime, and i know it's because it doesn't recognise the XmlElement LogRecord i added while serializing.. Is there any way to read this xml element so i can take the right property values?

Ps.抱歉,如果我弄乱了这些变量,当我在此处添加变量时,我试图简化代码,而且我可能混入了一些变量.

Ps. Sorry if i have messed up the variables, i tried to simplify the code when i added it here and i may have mixed some variables..

谢谢.

推荐答案

您可以在xml中手动添加根元素.因此,阅读时还必须手动跳过它.

You manually add the root element in the xml. Therefore, you must also manually skip it when reading.

XmlSerializer deserializer = new XmlSerializer(typeof(LogRecord));

using (var xmlReader = XmlReader.Create("LogRecords.xml"))
{
    // Skip root element
    xmlReader.ReadToFollowing("LogRecord");

    LogRecord record = (LogRecord)deserializer.Deserialize(xmlReader);
}

删除 [XmlRoot("LogRecords")] 属性以使其正常工作.

Remove the [XmlRoot("LogRecords")] attribute to make it work.

当然,您将始终在xml中获得第一个元素.

Of course, you will always get the first element in the xml.

如评论中所建议,使用列表.

As already suggested in the comments, use the list.

List<LogRecord> logRecords = new List<LogRecord>();

var logRecord = new LogRecord { ... };

// Store each new logRecord to list
logRecords.Add(logRecord);


var serializer = new XmlSerializer(typeof(List<LogRecord>));

// Serialization is done with just a couple lines of code.
using (var fileStream = new FileStream("LogRecords.xml", FileMode.Create))
{
    serializer.Serialize(fileStream, logRecords);
}

// As well as deserialization
using (var fileStream = new FileStream("LogRecords.xml", FileMode.Open))
{
    logRecords = (List<LogRecord>)serializer.Deserialize(fileStream);
}

因此,使用 XmlDocument 成为不必要的操作,而大惊小怪的是手动添加-跳过根节点.

Thus become unnecessary manipulation using XmlDocument and fuss with manually adding-skipping the root node.

这篇关于反序列化C#时阅读xml元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆