3

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>

2 Answers 2

7

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"];  
Sign up to request clarification or add additional context in comments.

2 Comments

Why does every single answer on StackOverflow that uses LINQ-to-XML involve .Descendants? Why recursively search the whole document for the elements when they're known to be the children of the root element? Just wondering...
@dtb: That's a fair criticism - it's easier/shorter to prototype and makes less assumptions about your xml structure but for large xml documents it would make a difference
-1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.