GuidoG
GuidoG

Reputation: 12059

How to find a value from a specific element by name?

I have an XML file, that looks like this (only a snippet)

 <?xml version="1.0" encoding="UTF-8" ?> 
 <Message>
   <Header>
      <Message_Type>RFP</Message_Type> 
      <Message_Date>2020-11-05T09:36:03+01:00</Message_Date> 
      <Sequence_Number>225</Sequence_Number> 
   etc...

I am looking for the fastest way to find the value RFP.
All i know is the elements name that I need to get a value for.

for example, I get names like Message_Type and Message_Date and now I need to get the value for these element names.
There are no attributes in the xml

I did some searching and all I can find is how to find an element with a specific attribute, or all elements with a specific value, stuff like that.
It seems like something very basic but i just cant see how to do it.

I tried something like this

var headerElements = XElement.Load(fileName).Elements("Header");
var element = headerElements.Where(x => x.Element("Message_Type").Name == "Message_Type");

this fills element with the entire Header which seems useless to me. I only need the value of one element in ´Header`, not all

So could some kind soul here put me in the right direction on how to do this ?

Upvotes: 1

Views: 200

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1502546

Your current query is using a Where call, which will only filter - it doesn't change which elements you're looking at.

What you want is just the Element method itself:

var messageTypeElements = headerElements.Elements("Message_Type");

That will give you all the <Message_Type> elements from all the Header elements.

If in fact you only have a single <Header> and a single <Message_Type> then you can use Element instead:

var message = XElement.Load(fileName);
var header = message.Element("Header");
var messageType = header.Element("Message_Type");

(The Element method will return the first element with the given name, or null if there aren't any. We don't know whether your program should just throw an exception if there are no headers/message_types, or handle it more gracefully.)

Upvotes: 4

Related Questions