我尝试使用Linq在C#中解析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;
}
此代码为我提供名字和姓氏。
我使用这个网站作为学习的参考。
答案 0 :(得分:3)
对于像你这样没有复杂命名空间的深层XML层次结构,我更喜欢usr.Roles
命名空间中的XPathSelectElements
。
假设您的public IQueryable<UserRoles> GetUsers()
{
var userQuery = (from usr in context.Users
join userRole in context.Set<IdentityUserRole>() on usr.Id equals userRole.UserId
join role in context.Roles on userRole.RoleId equals role.Id
group role by usr into roleGroup
select new UserRoles()
{
User = roleGroup.Key,
Roles = roleGroup.AsQueryable()
});
return userQuery;
}
元素与您的问题中显示的XML完全一致,您可以这样做:
System.Xml.XPath
纯Linq到XML的等价物是:
xelement
如您所见,它看起来有点复杂。
答案 1 :(得分:0)
使用Descendant()
和Descendants()
代替
foreach (var item in Credit)
{
dt.BORROWERFIRSTNAME = item.Descendant("FirstName").Value;
dt.BORROWERLASTNAME= item.Descendant("LastName").Value;
}