Using Linq to XML using C#, how do I find attribute values? - linq

I need to get all activities for specific claim ID = 13 using linq C#, I am trying the below code, but it's not working.
XDocument Doc = XDocument.Load(DownloadedPath);
var Activites = (from e in Doc.Descendants("Activity")
where (string)Doc.Element("Claim").Element("ID") == 13
below is the Xml
<?xml version="1.0" encoding="utf-8"?>
<Advice>
<Claim>
<ID>12</ID>
<ProviderID>CL-MC-0012-07</ProviderID>
<Activity>
<ID>20131520320</ID>
<Start>24/07/2013 13:00</Start>
<Type>3</Type>
</Activity>
<Activity>
<ID>20131520321</ID>
<Start>24/07/2013 13:00</Start>
<Type>3</Type>
</Activity>
</Claim>
<Claim>
<ID>13</ID>
<ProviderID>CL-MC-0012-07</ProviderID>
<Activity>
<ID>20132058590</ID>
<Start>20/10/2013 09:00</Start>
<Type>3</Type>
</Activity>
<Activity>
<ID>20132058591</ID>
<Start>20/10/2013 09:00</Start>
<Type>3</Type>
</Activity>
</Claim>

You're currently converting the value to a string but then comparing it with an int. Don't do that - it's not going to work :)
It's probably simplest to convert it to an int instead:
var Activites = (from e in Doc.Descendants("Activity")
where (int)Doc.Element("Claim").Element("ID") == 13
...)
Next, look at your XML - the Claim element isn't inside an Activity element... you probably just want:
var activities = doc.Descendants("Claim")
.Where(claim => (int) claim.Element("ID") == 13)
.SelectMany(claim => claim.Elements("Activity"));
This finds all Claim elements with an ID of 13 (of which there will probably only be one) and then selects its activities, using SelectMany so that the result will be a sequence of activity elements, rather than a sequence of sequences...

Related

LINQ XML query by attribute and nested element

I'm new to LINQ and am attempting to query an XML file by attribute and a descendant element value.
Here's a snip of my XML:
<redirurl>
<exceptionList state="FL">
<exception>
<plancode>ZZ</plancode>
<url>https://zzzz.com</url>
</exception>
</exceptionList>
<exceptionList state="NC">
<exception>
<plancode>AA</plancode>
<url>https://aaaa.com</url>
</exception>
<exception>
<plancode>BB</plancode>
<url>https://bbbb.com</url>
</exception>
</exceptionList>
</redirurl>
I'm trying to retrieve the value for url by state and plancode. For example, if the exceptionList state attribute = "NC" and the plancode = "BB", I want to get the url of "https://bbbb.com".
Here's my code:
var xmlFilePath = "myFilePathHere";
XElement xelement = XElement.Load(xmlFilePath );
IEnumerable<XElement> urlAddress = from el in xelement.Elements("exceptionList")
where (string)el.Attribute("state") == "NC"
&& (string)el.Element("exception").Element("plancode") == "BB"
select el;
I can't get the query right to save my life. If I omit the third line of the query (plancode line), I get the entire exceptionList node as a result. I suppose I could loop through it to get the plancode, but that doesn't seem like the right thing to do. The query as is does not return results. I've spent about 10 hours on this, doing tutorials and looking at code examples, but I'm just not getting it. Can someone advise what I'm missing? Thanks in advance.
Here is a Linq sequence that does as you ask:
XDocument doc = XDocument.Parse("<redirurl><exceptionList state=\"FL\"><exception><plancode>ZZ</plancode><url>https:////zzzz.com</url></exception></exceptionList><exceptionList state=\"NC\"><exception><plancode>AA</plancode><url>https:////aaaa.com</url></exception><exception><plancode>BB</plancode><url>https:////bbbb.com</url></exception></exceptionList></redirurl>");
var urlIWant = doc.Root.Descendants("exceptionList").Where(x => x.Attribute("state").Value == "NC").FirstOrDefault()
.Descendants("exception").Where(z => z.Descendants("plancode").FirstOrDefault().Value == "BB")
.FirstOrDefault().Descendants("url").FirstOrDefault().Value;

How to return multiple elements in a single XPath query using Groovy

I would like to know if its possible using Xpath to return mutliple elements from a single Xpath query without the use of the union '|' operator?
The problem I have is that I want to return two elements that are at different levels of the XML structure (employment_information.person_id_external and job_information.start_date) in one Xpath query from the following XML:
<CompoundEmployee>
<person>
<person_id_external>21554</person_id_external>
<employment_information>
<start_date>2014-02-27</start_date>
<job_information><end_date>2013-04-21</end_date><event>H</event><start_date>2012-09-28</start_date></job_information>
<job_information><end_date>2013-04-26</end_date><event>5</event><start_date>2013-04-22</start_date></job_information>
<job_information><end_date>9999-12-31</end_date><event>R</event><start_date>2014-02-27</start_date></job_information>
</employment_information>
</person>
<person>
<person_id_external>8265</person_id_external>
<employment_information>
<start_date>2000-10-02</start_date>
<job_information><end_date>2014-10-24</end_date><event>5</event><start_date>2014-05-22</start_date></job_information>
<job_information><end_date>2014-05-21</end_date><event>H</event><start_date>2000-10-02</start_date></job_information>
<job_information><end_date>9999-12-31</end_date><event>5</event><start_date>2014-10-25</start_date></job_information>
</employment_information>
</person>
<execution_timestamp>2015-05-05T08:17:51.000Z</execution_timestamp>
<version_id>1502P0</version_id>
</CompoundEmployee>
and the XPath query I've written so far is:
XPath x = XPath.newInstance("/*/*/*/job_information[number(translate(start_date,'-','')) < number(translate(../start_date,'-','')) and (event = 'H' or event = 'R')]/start_date");
Employees = x.selectNodes(doc);
for (Element Employee : Employees) {
fieldName = Employee.getName();
fieldValue = Employee.getText();
println ("Job Information Selection ${fieldName} = ${fieldValue}");
}
which works but only returns the job_information.start_date. If I union the same query but return employment_information.person_id_external the query returns them on two rows - 1 row per union but I want them returned on the same row but as two fields, if that makes sense. Can I do this? And if so how do I do it?
Thanks,
Greg

Rea XML files in WP7

I have an xml file with the following data
<?xml version="1.0" encoding="UTF-8"?>
<dataroot xmlns:od="urn:schemas-microsoft-com:officedata" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="NAMEDAYS.xsd" generated="2012-08-16T21:47:41">
<NAMEDAYS>
<DAY>1</DAY>
<MONTH>1</MONTH>
<NAMEDAY>New Years Day</NAMEDAY>
</NAMEDAYS>
<NAMEDAYS>
<DAY>6</DAY>
<MONTH>1</MONTH>
<NAMEDAY>Holly Spirit</NAMEDAY>
</NAMEDAYS>
The first element is the day then the month and finally the holiday.
I want to search the xml file for a specific day and month and return the holiday of that date.
Can you help me?
At first you have to create a sample class( for ex: MySampleClass) which will be used to store the XML element values and then you need to filter the data in a similar way:
XDocument loadedCustomData = XDocument.Load("CustomData.xml");
var filteredData = from c in loadedCustomData.Descendants("NAMEDAYS")
where c.Attribute("DAY").Value == "1" && c.Attribute("MONTH").Value == "1"
select new MySampleClass()
{
//set your properties here
};
listBox1.ItemsSource = filteredData;

Read xml data using XDocument class

I have an xml file say (test.xml)
<root loc-ver="1.0">
<data name="String1" xml:space="preserve">
<value loc="root_data_value_2">Description number1</value>
</data>
<data name="String2" xml:space="preserve">
<value loc="root_data_value_3">Description number 2</value>
</data>
</root>
Now, if
I specify the name = "String1", I should get the value as "Description number1"
I specify the name = "String2", I should get the value as Description number2
I am trying with the approach, by no result
XDocument doc = XDocument.Load(#"D:\test.xml");
string search = "String10";
var lv1s = from lv1 in doc.Descendants("data")
select lv1.Name;
Sounds like you want:
string name = "String1"; // Or whatever
var query = from data in doc.Descendants("data")
where (string) data.Attribute("name") == name
select (string) data.Element("value");
string description = query.First(); // Or FirstOrDefault etc
You should consider what you want to happen if there isn't exactly one result. Is that an error state (if so, use Single()), should you use all the results (if so, just iterate over query), should you use the first result if it's available, and ignore it otherwise (if so, use FirstOrDefault() and check if the result is null), should you use the first result, and it's an error if there aren't any (if so, use First()).

Linq to XML Noob question - distinct and order by on attributes

I'm just getting started using Linq to XML and I have a simple document with records like this:
<record date="6/27/2002" symbol="DG" price="15.00" />
I want a list of distinct symbols as strings, in order.
This gives me an unordered list of all attributes, but I'm stuck
var query =
from e in xml.Elements()
select e.Attribute("symbol");
How can this be modified to give me what I want?
How about:
var query = (from e in xml.Elements()
let symbol = (string)e.Attribute("symbol")
where symbol != null
orderby symbol
select symbol).Distinct();
I'd do that with lambda syntax:
var query = xml.Elements()
.Select(e => (string)e.Attribute("symbol"))
.Distinct()
.OrderBy(x=>x);

Resources