Reputation: 9435
XML
<?xml version="1.0" encoding="utf-8" ?>
<Employees>
<Employee>
<EmpId>1</EmpId>
<Name>Sam</Name>
<Sex>Male</Sex>
<Salary>40000</Salary>
<Phone Type="Home">423-555-0124</Phone>
<Phone Type="Work">424-555-0545</Phone>
<Address>
<Street>7A Cox Street</Street>
<City>Acampo</City>
<State>CA</State>
<Zip>95220</Zip>
<Country>USA</Country>
</Address>
</Employee>
<Employee>
<EmpId>2</EmpId>
<Name>Lucy</Name>
<Sex>Female</Sex>
<Salary>20000</Salary>
<Phone Type="Home">143-555-0763</Phone>
<Phone Type="Work">434-555-0567</Phone>
<Address>
<Street>Jess Bay</Street>
<City>Alta</City>
<State>CA</State>
<Zip>95701</Zip>
<Country>USA</Country>
</Address>
</Employee>
LINQ expression c#
var Pro = from u in doc.Descendants("Employee") select u;
foreach (var x in Pro)
{
Response.Write(string.Format("EMP ID: {0}, Emp Name: {1}", x.Element("EmpId"), x.Element("Name")));
}
I'm able to query the fields like EmpID, Name, Salary, etc.
But How to query the Address fields like Street, City, State, Zip, Country?
Thanks in advance.
Upvotes: 0
Views: 78
Reputation: 609
The Address elements you are trying to look for can be accessed by first selecting all the Address elements by using x.Elements("Address")
. Each nested Address element can then be selected using the .Element()
function.
So the parameters for Response.Write()
should look something like:
x.Elements("Address").Element("Street");
Upvotes: 0
Reputation: 610
I would also do what Reniuz suggested and deserialize to an object but here is an example of how you currently do it:
foreach (var x in Pro)
{
Response.Write("EMP ID: {0}, Emp Name: {1}\r\n", x.Element("EmpId"), x.Element("Name"));
var adrs = x.Descendants("Address");
foreach (var a in adrs)
{
Response.Write("\tAddress Street: {0}, City: {1}\r\n", a.Element("Street"), a.Element("City"));
}
}
Upvotes: 1
Reputation: 4906
Take XML into the Variable and Use Like
XDocument doc = XDocument.Parse(XMLVariableString);
var FirstPart = from node in doc.Descendants("items") select node; //Select Data from doc using
List<ListName> valuesNodes = new List<ListName>(); //create any with i.e <==
Create One List
with the Same Name as in XML
and Created Sub List
for Address
Containing the all the fields of Address
Use the Same Query you have used but select from FirstPart
.
Now you can easily handle data from var FirstPart
Upvotes: 0