here i am trying to get custName name if pirmaryCustCheck is true if not then i have to select false tag element , how can i achieve this xml :
<Root>
<data>
<office>Mumba</office>
<officeId>1JC9FJBM</officeId>
<customer>
<custName>Yash</custName>
<pirmaryCustCheck>true</pirmaryCustCheck>
<id>8</id>
</customer>
<customer>
<custName> Rahul</custName>
<pirmaryCustCheck>false</pirmaryCustCheck>
<id>9</id>
</customer>
</data>
</Root>
code :
string pathd = @"C:\Users\admin\documents\newCust.xml";
XDocument docss = XDocument.Load(pathd);
var records = docss.Descendants("data").Select(x => new
{
office = (string)x.Element("office"),
officeId = (string)x.Element("officeId"),
customer = x.Elements("customer").Select(y => new
{
custName = (string)y.Element("custName"),
pirmaryCustCheck = (bool)y.Element("pirmaryCustCheck"),
id = (string)y.Element("id")
}).Where(y => y.pirmaryCustCheck == true).Select(c => new
{
custName = c.custName,
Id = c.id
})
}).FirstOrDefault();
You may want to try something like below.
Data Set
<Root>
<data>
<office>Mumba</office>
<officeId>1JC9FJBM</officeId>
<customer>
<custName>Yash</custName>
<pirmaryCustCheck>true</pirmaryCustCheck>
<id>8</id>
</customer>
<customer>
<custName> Rahul</custName>
<pirmaryCustCheck>false</pirmaryCustCheck>
<id>9</id>
</customer>
</data>
<data>
<office>Mumba</office>
<officeId>1JC9FJBM</officeId>
<customer>
<custName>Yash</custName>
<pirmaryCustCheck>false</pirmaryCustCheck>
<id>11</id>
</customer>
<customer>
<custName> Rahul Jain</custName>
<pirmaryCustCheck>false</pirmaryCustCheck>
<id>10</id>
</customer>
</data>
Code -
string pathd = @"C:\Users\admin\documents\newCust.xml";
XDocument docss = XDocument.Load(pathd);
var customerTrue = docss.Descendants("data").Elements("customer").Select(x => x).FirstOrDefault();
var customerFalse = docss.Descendants("data").Elements("customer").Select(x => x).LastOrDefault();
var records = docss.Descendants("data").Select(x => new
{
office = (string)x.Element("office"),
officeId = (string)x.Element("officeId"),
customer = new
{
custName = (bool)x.Elements("customer").First().Element("pirmaryCustCheck") ? (string)x.Elements("customer").First().Element("custName") : (string)x.Elements("customer").Last().Element("custName"),
pirmaryCustCheck = (bool)x.Elements("customer").First().Element("pirmaryCustCheck"),
id = (bool)x.Elements("customer").First().Element("pirmaryCustCheck") ? (string)x.Elements("customer").First().Element("id") : (string)x.Elements("customer").Last().Element("id")
}
}).ToList();
Try below code, its tested.
var customers = (from e in docss.Descendants("data").Elements("customer")
where (bool)e.Element("pirmaryCustCheck") == true
select new
{
Name = (string)e.Element("custName"),
Id = (string)e.Element("id"),
}).ToList();
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.