简体   繁体   中英

Querying the nested xml using linq by specifying attribute value

MY xml schema like this:

  <TestSuite>

  <TestCase Name="Connect">
    <Input>
      <AppName>XYZ</AppName>
      <UserId>Vishwas</UserId>    
    </Input>
  </TestCase>

  <TestCase Name="Create">
    <Input>
      <FileName>abc</AppName>    
    </Input>
    <OutPut>
      <Filesize></Filesize>
  </TestCase>  

 <TestSuite>

How can i write a LINQ to XML query to retrieve the value of UserId, which is present inside Test case name "Connect", i am new to linq expecting your help and advance thanks.

First of all your XML is not well formed, I have corrected that in code, change it accordingly.

You can do it either by going from TestCase till UserId like this:-

var xdoc = XDocument.Parse(@"<TestSuite><TestCase Name=""Connect""><Input>
 <AppName>XYZ</AppName><UserId>Vishwas</UserId></Input></TestCase>
 <TestCase Name=""Create""><Input><FileName>abc</FileName></Input><OutPut>
 <Filesize></Filesize></OutPut></TestCase></TestSuite>");

string userid = (xdoc.Descendants("TestCase")
                     .Where(x => (string)x.Attribute("Name") == "Connect")
                     .Select(x => (string)x.Element("Input").Element("UserId")))
                     .FirstOrDefault();

Or you can select Input node then you can both filter and select item like this:-

string userid = (from x in xdoc.Descendants("Input")
                 where (string)x.Parent.Attribute("Name") == "Connect"
                 select (string)x.Element("UserId")).FirstOrDefault();

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