简体   繁体   English

使用 Linq 有条件地删除 XML 文档的部分

[英]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?我将如何使用 Linq 删除其元素<CC>不具有值 0123 的所有<CCInfo>部分?

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通缉 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 :查询CCInfo节点,将CC元素的值与您想要的值进行比较,然后调用XNode.Remove method

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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