0

I have the following XML and that is loaded using the path variable

<testdata>
  <payloaddata>
    <Data Name="testdataone">
      <Id>101</Id>
      <Value>data1</Value>
    </Data>
    <Data Name="testdata2">
      <Id>102</Id>
      <Value>2</Value>
    </Data>
  </payloaddata>
  <VerifyData>
    <Data Name="veridyData">
      <Id>301</Id>
      <Value>true</Value>
    </Data>
  </VerifyData>
</testdata>

I need to retreive the value element data with id 101. Meaning if queried for "101" i should get "data1".

I have written the following is this fine, or can this be more optimized? or written better? I am new to LINQ

XDocument document = XDocument.Load(path);
            var query = from data in document.Descendants("payloaddata").Descendants("Data")
                        where (string)data.Element("Id").Value == "101"
                        select new
                                   {
                                       payloadData = data.Element("Value").Value
                                   };

            foreach (var employee in query)
            {
                Console.WriteLine(employee.payloadData);
            }
siva
  • 1,135
  • 4
  • 17
  • 25
  • 6
    Hello again. Does that code work as you expect? If so, your question would be a better fit for [codereview.se]. – Frédéric Hamidi Feb 02 '15 at 11:32
  • Frederic : Yes it works – siva Feb 02 '15 at 11:33
  • Seleman for now just payloaddata – siva Feb 02 '15 at 11:34
  • 1
    Just be sure to include sufficient context of wwhat it is that your code is doing if/when you post it on Code Review! – Simon Forsberg Feb 02 '15 at 11:38
  • Also, Xelement.Value is already of string type . So you don't need to typecast in a string again. – Rohit Prakash Feb 02 '15 at 11:46
  • if you need optimization (it won't change anything with the sample given, but with a really large xml, it may be usefull), don't use Descendants, but Element / Elements with the correct path : something like that, may vary if you may have many "payloaddata" nodes or not : `document.Root.Element("payloaddata").Elements("Data")` . See for example this to understand the difference : http://stackoverflow.com/questions/3705020/what-is-the-difference-between-linq-to-xml-descendants-and-elements – Raphaël Althaus Feb 02 '15 at 12:05

0 Answers0