简体   繁体   English

使用LINQ to XML解析XML?

[英]Parse XML using LINQ to XML?

I try to use Linq to parse a XML in C#. 我尝试使用Linq在C#中解析XML。

this is the XML I am parsing: 这是我正在解析的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>

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 http://www.dotnetcurry.com/showarticle.aspx?ID=564

For deep XML hierarchies like yours without complex namespaces, I prefer XPathSelectElements in the System.Xml.XPath namespace. 对于像您这样的没有复杂名称空间的深层XML层次结构,我更喜欢System.Xml.XPath名称空间中的XPathSelectElements

Assuming that your xelement element has exactly the XML shown in your question, you can do: 假设您的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.
}

The equivalent in pure Linq to XML is: 从Linq到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.
}

As you can see, it looks a bit more complicated. 如您所见,它看起来有点复杂。

use Descendant() and Descendants() instead 使用Descendant()Descendants()代替

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM