如何使用 LINQ 获取特定节点 XML 的子元素
本文关键字:XML 元素 节点 何使用 LINQ 获取 | 更新日期: 2023-09-27 18:33:55
我需要获取声明 ID = "0000526_INS012_5367676737" 以下 xml 的所有活动
<?xml version="1.0" encoding="utf-8"?>
<Header>
<SenderID>INS012</SenderID>
<ReceiverID>F-0000526</ReceiverID>
<TransactionDate>04/11/2014 01:07</TransactionDate>
<RecordCount>1</RecordCount>
<DispositionFlag>PRODUCTION</DispositionFlag>
</Header>
<Claim>
<ID>DHA-F-0000526_INS012_20141007135247</ID>
<IDPayer>16175815</IDPayer>
<ProviderID>F-0000526</ProviderID>
<Encounter>
<FacilityID>DHA-F-0000526</FacilityID>
</Encounter>
<Activity>
<ID>779972</ID>
<Start>07/10/2014 13:53</Start>
<Type>5</Type>
</Activity>
<Activity>
<ID>779973</ID>
<Start>07/10/2014 13:53</Start>
<Type>5</Type>
</Activity>
</Claim>
<Claim>
<ID>0000526_INS012_5367676737</ID>
<IDPayer>16175815</IDPayer>
<ProviderID>F-0000526</ProviderID>
<Encounter>
<FacilityID>DHA-F-0000526</FacilityID>
</Encounter>
<Activity>
<ID>6767</ID>
<Start>07/10/2014 13:53</Start>
<Type>5</Type>
</Activity>
<Activity>
<ID>67467</ID>
<Start>07/10/2014 13:53</Start>
<Type>5</Type>
</Activity>
</Claim>
</Remittance.Advice>
我尝试在下面做代码,但它不起作用
var oooo = Doc.Descendants("Claim").Where(claim => claim.Element("ID").ToString() == ClaimList.CLAIM_ID)
.SelectMany(claim => claim.Elements("Activity"));
.ToString()
将返回元素的XML,包括其标记。
您需要使用 (string)
强制转换或 .Value
属性(我推荐前者,因为如果元素不存在.Value
将引发NullReferenceException
):
var oooo = Doc.Descendants("Claim")
.Where(claim => (string)claim.Element("ID") == ClaimList.CLAIM_ID)
.SelectMany(claim => claim.Elements("Activity"))
.Select(activity => new {
ID = (string)activity.Element("ID"),
Start = (string)activity.Element("Start"),
Type = (string)activity.Element("Type")
});;
试试这个:-
XDocument xdoc = XDocument.Load(@"YourXMLFile.xml");
var result = xdoc.Root.Descendants("Claim")
.Where(x => x.Element("ID").Value == "0000526_INS012_5367676737")
.Select(x => x.Descendants("Activity")
.Select(z => new
{
ID = z.Element("ID").Value,
Start = z.Element("Start").Value,
Type = z.Element("Type").Value
}).ToList());