c#如何获取特定节点 XML 与 linq 的子元素

标签: Linq XML C#
发布时间: 2017/2/28 21:26:28
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

我需要得到所有activity为索赔 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"));

解决方法 1:

.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")
               });;
官方微信
官方QQ群
31647020