【发布时间】:2019-05-28 06:05:37
【问题描述】:
我有一些关于读取 xml 文件的问题。我必须将 xml 标签填充为类属性。有没有办法解决这个问题?
我查看了每篇 xml 序列化文章。当我尝试运行我的代码时,我从类中得到了空值
这是我的 Program.cs
Log lg = new Log();
XmlReader reader = XmlReader.Create(@"C:\Logs\Workflow User
Functions\2019\05\15\01.xml");
while (reader.Read())
{
if (reader.HasAttributes && lg.date !=null && lg.datetime !=null)
{
Console.WriteLine(reader.GetAttribute(lg.date) +
reader.GetAttribute(lg.datetime));
}
}
Console.ReadLine();
还有我的 Log.cs
[XmlAttribute(AttributeName ="date")]
public string date { get; set; }
[XmlAttribute(AttributeName = "datetime")]
public string datetime { get; set; }
还有我尝试获取属性值的 xml 文件
<?xml version="1.0"?><Logs version="1" appname="Workflow User Functions" id="fed9fc29-f6bf-4814-8401-f8742ea0ceef" date="15/30/2019 01">
<Log id="" logtype="Error" datetime="30:52" user="workflow" logname="ScheduledJobs.fnExecute_Execute">Process Id : 69705
【问题讨论】:
-
你能分享
Log类的完整代码吗?即minimal reproducible example?lg.date和lg.datetime怎么样,为什么在分配lg后它们会立即为非空? -
您的 XML 格式不正确。如果我将它上传到xmlvalidation.com,我会收到一个错误,XML 文档中的错误:XML 文档结构必须在同一个实体内开始和结束。
-
也许你想使用
nameof,即reader.GetAttribute(nameof(lg.date)) && reader.GetAttribute(nameof(lg.datetime))?在这种情况下,您将在 XML 中搜索与date和datetime成员具有相同名称而不是相同值的属性。 (另外,nameof()永远不会返回null,所以删除&& lg.date !=null && lg.datetime !=null。)
标签: c# xml console console-application