Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read xml attribute with linq

<ARTICLE_PRICE_DETAILS>
        <DATETIME type="valid_start_date">
          <DATE>2015-07-01</DATE>
        </DATETIME>
        <DATETIME type="valid_end_date">
          <DATE></DATE>
        </DATETIME>
</ARTICLE_PRICE_DETAILS>

How can i get value in the Element?

I tried this one

   var productQuery = (from p in xmlDocument.Descendants("ARTICLE_PRICE_DETAILS")
                        select new
                        {

                            articleDatetime = p.Element("DATETIME")
                                               .Attribute("valid_start_date")
                                               .Value

                        });

when i try to use articleDatetime , i got an exception. need help to me

like image 804
Selman Avatar asked Jan 25 '26 01:01

Selman


1 Answers

Well, it looks like you're trying to get value of DATE element under DATETIME having atribute type="valid_start_date".

It can be done by various ways, here is one of them:

var dates = xmlDocument
     .XPathSelectElements("ARTICLE_PRICE_DETAILS/DATETIME[@type='valid_start_date']/DATE")
     .Select(e => e.Value)
     .ToList();

Notice here most of the job is done with XPathSelectElements method and appropriate xpath expression.

The same result can be achieved also without using xpath selection, only by a couple of linq calls like:

var xmlDocument = doc.Descendants("ARTICLE_PRICE_DETAILS")
                     .Descendants("DATETIME")
                     .Where(e => e.Attribute("type")?.Value == "valid_start_date")
                     .Descendants("DATE")
                     .Select(e => e.Value)
                     .ToList();

But it looks less readable (at least from my point of view).

like image 86
Andrey Korneyev Avatar answered Jan 27 '26 13:01

Andrey Korneyev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!