使用LINQ to XML查询XML [英] Querying XML with LINQ to XML
问题描述
大家好!
我的应用程序使用LINQ to XML XElement将消息跟踪到xml文件中.这是结果xml文件的示例:
Hi all!
My application traces messages into xml-file by using LINQ to XML XElement. Here is sample of result xml-file:
<xml version="1.0" encoding="utf-8"?>
<Messages>
<Message>
<timeStamp>10.12.2010 12:05:57</timeStamp>
<Level>Error</Level>
<PID>1256</PID>
<traceMessage>Error happened </traceMessage>
</Message>
<Message>
<timeStamp>10.12.2010 12:06:07</timeStamp>
<Level>Info</Level>
<PID>5168</PID>
<traceMessage>This is just info message</traceMessage>
</Message>
<Message>
<Messages>
现在,我的任务是创建WPF应用程序,该应用程序读取该xml文件并显示消息.问题是,消息级别有所不同(错误,信息),我需要创建一些仅显示所需消息的过滤器或查询.例如仅显示错误消息".我该怎么办?
还是有可能查询该格式,还是我必须稍微改变我的文件格式?请您帮忙.
希望你有我的主意:)
干杯
Now my task is to create WPF application which reads that xml file and shows messages. The problem is that message level varies (error, info.) and I need create some filter or query which shows only wanted messages. For example "show only Error messages". How do I do that?
Or is it even possible query that format or do I have to change little bit my file formation? I kindly ask your help.
I hope you got my idea :)
Cheers
推荐答案
如果您的traceMessage元素中始终带有错误词,那么如果包含错误,则可以基于字符串比较进行过滤,然后返回错误消息.
但是我建议您向消息元素"添加一个属性,例如显示一个类别,无论是错误还是信息.
喜欢
If your traceMessage Element have always Error word inside then you can filter based on string comparison if it contains Error then it''s Error message.
But I would suggest you to add one attribute to Message Element like to show a category whether it''s error or Info.
like
<Message Category="Error">
...
...
</Message>
<Message Category="Info">
...
...
</Message>
应用LINQ筛选数据将更加容易.
[更新]
啊!!感谢您更新raitu,我可以建议您执行可能对您有帮助的查询.
It will be easier to apply LINQ to filter data.
[Update]
Ah!! Thanks for updating raitu, I can suggest you following query that might help you.
var resultXML = from c in TraceMessage.Elements("Message")
where ((string)c.Element("traceMessage")).Contains("Error")
select new {
Timestamp = (String)c.Element("timestamp"),
Level = (string)c.Element("Level"),
PID = (string)c.Element("PID"),
traceMessage = (string)c.Element("tracemessage") };
这篇关于使用LINQ to XML查询XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!