2015-06-16 85 views
0

我嘗試使用Linq來解析C#中的XML。使用LINQ to XML解析XML?

這是我解析XML:

<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> 

,這是我的代碼來分析它:

 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; 
     } 

這段代碼給我名字和姓氏。

  1. 首先,我想知道這是否正確的解析方式?
  2. 秒如果我想獲得當前或以前的地址我怎麼能得到它們?在某些情況下,以前的地址也可能不存在。

我已經使用這個網站作爲學習的參考。

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

+0

這個問題與linq有什麼關係? – Jashaszun

+1

@Jashaszun也許使用'System.Xml.Linq'命名空間中的類? – vesan

+0

我編輯過你的標題。請參閱:「[應該在其標題中包含」標籤「](http://meta.stackexchange.com/questions/19190/)」,其中的共識是「不,他們不應該」。 –

回答

3

對於深層次的XML像你無需複雜的命名空間,我喜歡在System.Xml.XPath命名空間XPathSelectElements

假設在你的問題你xelement元素恰有所示的XML,你可以這樣做:

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. 
} 

等效於純的LINQ to XML是:

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. 
} 

正如你所看到的,它看起來更復雜一點。

+0

謝謝你的回答是正確和完整的。 – Alma

0

使用Descendant()Descendants()代替

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

您應該嘗試回答第二個問題:'如果我想獲取當前或以前的地址,我如何獲得它們?' – Jashaszun

+0

@Andrew謝謝,但Descendant在我的代碼中不可用。我有後代。不知道如何使用它。 – Alma

+0

'.Descendants(「FirstName」)[0]'爲你編譯? – maksymiuk