I try to use Linq to parse a XML in C#.
this is the XML I am parsing:
<Credit>
<LoanApp>
<LoanAppRq PaymentCall="True" Personal="True" Type="Finance">
<Applicant>
<Personal>
<Individuals>
<Individual Type="Applicant">
<GivenName>
<FirstName>test</FirstName>
<LastName>tester</LastName>
</GivenName>
<ContactInfo>
<Address Type="Current">
<StreetNumber>6</StreetNumber>
<StreetName>alton AVE</StreetName>
<City>PHILADELPHIA</City>
<State>PA</State>
<Zip>19142</Zip>
<TimeAtLocation>
<Year>6</Year>
<Month>0</Month>
</TimeAtLocation>
</Address>
<Address Type="Previous">
<StreetNumber>83</StreetNumber>
<StreetName>Main Street</StreetName>
<StreetExtra>12</StreetExtra>
<City>Irvine</City>
<State>CA</State>
<Zip>92695</Zip>
<Country>USA</Country>
<TimeAtLocation>
<Year/>
<Month>3</Month>
</TimeAtLocation>
</Address>
</ContactInfo>
and this is my code to parse it:
parsed_xml.LoadXml(dto.xml);
XElement xelement = XElement.Load(stream);
IEnumerable<XElement> Credit = xelement.Elements();
foreach (var item in Credit)
{
dt.BORROWERFIRSTNAME = item.Element("LoanApp").Element("LoanAppRq").Element("Applicant").Element("Personal").Element("Individuals").Element("Individual").Element("GivenName").Element("FirstName").Value;
dt.BORROWERLASTNAME= item.Element("LoanApp").Element("LoanAppRq").Element("Applicant").Element("Personal").Element("Individuals").Element("Individual").Element("GivenName").Element("LastName").Value;
}
this code give me the Firstname and lastname.
- First of all I wanted to know if this the correct way to parsing or not?
- second if I want to get Current or previous address how I can get them? Also the previous address may not existed in some situation.
I have used this website as a reference for learning.
For deep XML hierarchies like yours without complex namespaces, I prefer
XPathSelectElements
in theSystem.Xml.XPath
namespace.Assuming that your
xelement
element has exactly the XML shown in your question, you can do:The equivalent in pure Linq to XML is:
As you can see, it looks a bit more complicated.