简体   繁体   中英

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. What would be the best method for querying the values out where Name = x and Get the related Value?

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.

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:

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.

Judging by your xml it looks like you could also benefit from projecting to a dictionary (if your Name element values are unique):

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. For example, the XPath to get System ID would be:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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