简体   繁体   中英

Need help to query a complex XML using LINQ for a complex xml structure

Can someone tell me how to query the below xml using LINQ to get name of the books written by John.I am completely new to linq and it would be great if you can help me on this. I tried to write some queries but it didnt work.

<Library>
<Name>Central Library</Name>
<Address>
<Place>West Fort</Place>
<Pin>0088</Pin>
</Address>
<Books>
<Book>
  <Name>Book1</Name>
   <Specifications>
     <Specification>
      <Name>status</Name>
      <value><![CDATA[available]]></value>
     </Specification>
     <Specification>
      <Name>Author</Name>
      <value><![CDATA[John]]></value>
     </Specification>
  </Specifications>
</Book>
<Book>
 <Name>Book2</Name>
  <Specifications>
   <Specification>
    <Name>status</Name>
    <value><![CDATA[Not available]]></value>
   </Specification>
   <Specification>
    <Name>Author</Name>
   <value><![CDATA[Smith]]></value>
   </Specification>
</Specifications>
</Book>
<Book>
<Name>Book3</Name>
 <Specifications>
  <Specification>
   <Name>status</Name>
   <value><![CDATA[Not available]]></value>
  </Specification>
  <Specification>
   <Name>Author</Name>
   <value><![CDATA[John]]></value>
 </Specification>
</Specifications>
</Book>
</Books>
</Library>

You can do it like this:

var xmlDocument = XDocument.Load("Xml filePath");

var books = xmlDocument
            .Descendants("Specification")
            .Where(x => ((string) x.Element("value")).Contains("John"))
            .Select(x => x.Parent.Parent);

But keep in mind you shouldn't ask for code.First you should do some research, read documentation & tutorials, spend some effort then if you have problems abour your attempt(s) you should come and ask for those specific problems.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM