如何使用linq获取特定节点XML的子元素

时间:2014-12-11 13:40:05

标签: c# xml linq

我需要获得索赔的所有活动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"));

2 个答案:

答案 0 :(得分:0)

.ToString()将返回元素的XML,包括其标记。

你需要使用(string)强制转换或.Value属性(我推荐前者,因为如果元素不存在,.Value会抛出NullReferenceException:< / p>

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

答案 1 :(得分:0)

试试这个: -

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