简体   繁体   English

需要帮助使用 LINQ 查询复杂的 XML 以获取复杂的 xml 结构

[英]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.有人可以告诉我如何使用 LINQ 查询以下 xml 以获取 John 写的书名。我对 linq 完全陌生,如果您能在这方面帮助我,那就太好了。 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.但是请记住,您不应该要求代码。首先,您应该做一些研究,阅读文档和教程,花一些精力,然后如果您的尝试遇到问题,您应该来询问那些具体问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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