簡體   English   中英

如何使用linq獲取特定節點XML的子元素

[英]how to get child elements for specific node XML with linq

我需要在下面的xml中獲取索賠ID =“ 0000526_INS012_5367676737”的所有活動

<?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());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM