0

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.

  1. First of all I wanted to know if this the correct way to parsing or not?
  2. 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.

http://www.dotnetcurry.com/showarticle.aspx?ID=564

3
  • What does this question have to do with linq? Commented Jun 16, 2015 at 23:14
  • 1
    @Jashaszun Maybe using classes from the System.Xml.Linq namespace? Commented Jun 16, 2015 at 23:38
  • I have edited your title. Please see, "Should questions include “tags” in their titles?", where the consensus is "no, they should not". Commented Jun 16, 2015 at 23:47

2 Answers 2

3

For deep XML hierarchies like yours without complex namespaces, I prefer XPathSelectElements in the System.Xml.XPath namespace.

Assuming that your xelement element has exactly the XML shown in your question, you can do:

foreach (var individual in xelement.XPathSelectElements("LoanApp/LoanAppRq/Applicant/Personal/Individuals/Individual"))
{
    // Get the first and last name.
    var BORROWERFIRSTNAME = (string)individual.XPathSelectElement("GivenName/FirstName");
    var BORROWERLASTNAME = (string)individual.XPathSelectElement("GivenName/LastName");

    // Get the XElement for the current address.
    var currentAddress = individual.XPathSelectElements("ContactInfo/Address[@Type='Current']")
                                   .FirstOrDefault();
    // Extract its properties, checking for a missing current address if necessary.
    var currentZip = (currentAddress == null ? null : (string)currentAddress.Element("Zip"));

    // Get the XElement for the previous address.
    var previousAddress = individual.XPathSelectElements("ContactInfo/Address[@Type='Previous']")
                                    .FirstOrDefault();
    // Extract its properties, checking for a missing previous address if necessary.
    var previousZip = (previousAddress == null ? null : (string)previousAddress.Element("Zip"));

    // Process the borrower names and addresses as required.
}

The equivalent in pure Linq to XML is:

foreach (var individual in xelement.Elements("LoanApp")
                                   .Elements("LoanAppRq")
                                   .Elements("Applicant")
                                   .Elements("Personal")
                                   .Elements("Individuals")
                                   .Elements("Individual"))
{
    // Get the first and last name.
    var BORROWERFIRSTNAME = (string)individual.Elements("GivenName")
                                              .Elements("FirstName")
                                              .FirstOrDefault();
    var BORROWERLASTNAME = (string)individual.Elements("GivenName")
                                             .Elements("LastName")
                                             .FirstOrDefault();

    // Get the XElement for the current address.
    var currentAddress = individual.Elements("ContactInfo").Elements("Address").Where(e => (string)e.Attribute("Type") == "Current").FirstOrDefault();
    // Extract its properties, checking for a missing current address if necessary.
    var currentZip = (currentAddress == null ? null : (string)currentAddress.Element("Zip"));

    // Get the XElement for the previous address.
    var previousAddress = individual.Elements("ContactInfo").Elements("Address").Where(e => (string)e.Attribute("Type") == "Previous").FirstOrDefault();
    // Extract its properties, checking for a missing previous address if necessary.
    var previousZip = (previousAddress == null ? null : (string)previousAddress.Element("Zip"));

    // Process the borrower names and addresses as required.
}

As you can see, it looks a bit more complicated.

Sign up to request clarification or add additional context in comments.

Comments

0

use Descendant() and Descendants() instead

foreach (var item in Credit)
{
    dt.BORROWERFIRSTNAME = item.Descendant("FirstName").Value;
    dt.BORROWERLASTNAME= item.Descendant("LastName").Value;
}

3 Comments

You should try to answer the second question as well: if I want to get Current or previous address how I can get them?
@Andrew Thank you but Descendant is not available in my code. I have Descendants. not sure how to use it.
Does .Descendants("FirstName")[0] compile for you?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.