scarpacci
scarpacci

Reputation: 9194

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>

Upvotes: 3

Views: 1521

Answers (2)

Val Akkapeddi
Val Akkapeddi

Reputation: 1183

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

Upvotes: -1

BrokenGlass
BrokenGlass

Reputation: 160882

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"];  

Upvotes: 7

Related Questions