开发者

Conditionally remove sections of XML document with Linq

How would i using Linq remove all <CCInfo> section where their element <CC> does not have the value 0123 ?

Source document:

<Processing>
  <Mods>
    <ListMods>
      <Action>A</Action>
      <GetMoreInd></GetMoreInd>
      <QLDNameReq></QLDNameReq>
      <CCAry>
        <CCInfo>
          <CC>0123</CC>
          <Num>25</Num>
          <Cat></Cat>
          <DtRange></DtRange>
        </CCInfo>
        <CCInfo>
            <CC>456</CC>
            <Num>25</Num>
            <Cat></Cat>
            <DtRange></DtRange>
          </CCInfo>
          <CCInfo>
            <CC>0123</CC>
            <Num>99</Num>
            <Cat></Cat>
            <DtRange></DtRange>
          </CCInfo>
          <C开发者_运维问答CInfo>
            <CC>0123</CC>
            <Num>16</Num>
            <Cat></Cat>
            <DtRange></DtRange>
          </CCInfo>
          <CCInfo>
            <CC>xyz</CC>
            <Num>16</Num>
            <Cat></Cat>
            <DtRange></DtRange>
          </CCInfo>
        </CCAry>
      </ListMods>
  </Mods>
</Processing>

Wanted output

<Processing>
  <Mods>
    <ListMods>
      <Action>A</Action>
      <GetMoreInd></GetMoreInd>
      <QLDNameReq></QLDNameReq>
      <CCAry>
        <CCInfo>
          <CC>0123</CC>
          <Num>25</Num>
          <Cat></Cat>
          <DtRange></DtRange>
        </CCInfo>
          <CCInfo>
            <CC>0123</CC>
            <Num>99</Num>
            <Cat></Cat>
            <DtRange></DtRange>
          </CCInfo>
          <CCInfo>
            <CC>0123</CC>
            <Num>16</Num>
            <Cat></Cat>
            <DtRange></DtRange>
          </CCInfo>
        </CCAry>
      </ListMods>
  </Mods>
</Processing>

thanks


Query for the CCInfo nodes, compare the CC element's value against your desired value, then call the XNode.Remove method:

var query = xml.Descendants("CCInfo")
               .Where(e => e.Element("CC").Value != "0123");
query.Remove();
Console.WriteLine(xml);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜