简体   繁体   English

在C#中查询XML的最佳方法 - 使用LINQ等

[英]Best way to query XML in C# - using LINQ, etc

I have an xml message that I need to parse (No control of format) that looks something like the below (Name / Value Pairs) that I need to process. 我有一个xml消息,我需要解析(无格式控制),看起来像我需要处理的下面(名称/价值对)。 What would be the best method for querying the values out where Name = x and Get the related Value? 什么是查询Name = x和获取相关值的值的最佳方法?

I am currently using a nested select to try and get the value out of a specific Name / Value pair. 我目前正在使用嵌套选择来尝试从特定的名称/值对中获取值。 Just wondering if an easier LINQ / Lambda call I could use instead. 只是想知道我是否可以使用更简单的LINQ / Lambda调用。

Any suggestions would be appreciated. 任何建议,将不胜感激。

<Message>
<MessageContent>
  <MessageDetails>
    <Name>System_ID</Name>
    <Value>12345</Value>
  </MessageDetails>
  <MessageDetails>
    <Name>System_Name</Name>
    <Value>Test System</Value>
  </MessageDetails>
</MessageContent>
</Message>

Use Linq to XML: 使用Linq到XML:

var xml = XElement.Load(someXmlFile);
var results = xml.Descendants("MessageDetails")
                 .Where(m => m.Element("Name").Value == someValue)
                 .Select(m => m.Element("Value").Value);

If you expect only one match add a FirstOrDefault() to get the first matching value. 如果您只希望一个匹配,请添加FirstOrDefault()以获取第一个匹配值。

Judging by your xml it looks like you could also benefit from projecting to a dictionary (if your Name element values are unique): 从您的xml判断,看起来您也可以从投影到字典中受益(如果您的Name元素值是唯一的):

var dictionary = xml.Descendants("MessageDetails")
                    .ToDictionary(x => x.Element("Name").Value, 
                                  x => x.Element("Value").Value);

Now you can just use the dictionary: 现在你可以使用字典了:

string value = dictionary["System_ID"];  

If you have no control of the format, and it's likely to change in the future, I'd consider using XPath as well, so you can modify your selects with fewer code-changes. 如果您无法控制格式,并且将来可能会更改,我也会考虑使用XPath ,因此您可以使用更少的代码更改来修改选择。 For example, the XPath to get System ID would be: 例如,获取系统ID的XPath将是:

//MessageContent/MessageDetails[Name='System_Name']/Value

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM