简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM