【问题标题】:XML: How to remove an element from IEnumerable object?XML:如何从 IEnumerable 对象中删除元素?
【发布时间】:2013-09-11 12:37:55
【问题描述】:

我使用 XElement 类动态生成 XML 文件。感兴趣的序列如下所示:

<Actions>
    <Action Id="35552" MailRuId="100000">
      <ActionTypeId>2</ActionTypeId>
      <GenreTypeId>16</GenreTypeId>
    </Action>
    <Action Id="36146" MailRuId="100001">
      <ActionTypeId>7</ActionTypeId>
      <GenreTypeId>2</GenreTypeId>
      <ActionDate Id="127060" FreeTicketsCount="26" ReservedTicketsCount="3">06.09.2013 18:00:00</ActionDate>
    </Action>
</Actions>

如果“ActionDate”子节点没有退出,我想删除“Action”节点。

生成 XML 文件的代码如下:

var actionElement = new XElement("Action",
    new XElement("ActionTypeId", first.ActionTypeId),
    new XElement("GenreTypeId", first.GenreTypeId));

IEnumerable<XElement> seanceElements = infos
    .GroupBy(ti => ti.ActionDate)
    .Select(CreateSeanceElement);

actionElement.Add(seanceElements);

CreateSeanceElement 方法创建“ActionDate”节点,但正如我所说的,它可以或不能创建。

【问题讨论】:

    标签: c# xml xelement


    【解决方案1】:

    选择所有没有ActionDate元素的元素(即它为null)并将它们从actions元素中删除:

    actions.Elements("Action")
           .Where(a => a.Element("ActionDate") == null)
           .Remove();
    

    顺便说一句,如果您正在生成 XML,请考虑不要添加此类元素。这比添加和删除要好。

    【讨论】:

    • IEnumerable&lt;XElement&gt;Remove 方法吗?
    • IEnumerable 没有 Remove 方法。
    • @Romoku 是的,它有 Extensions.Remove<T> Method
    【解决方案2】:

    我再举一个例子:

         XDocument doc = XDocument.Load("D:\\tmp.xml");
         List<XElement> elements = new List<XElement>();
    
         foreach (XElement cell in doc.Element("Actions").Elements("Action"))
         {
            if (cell.Element("ActionDate") == null)
            {
               elements.Add(cell);
            }
         }
    
         foreach (XElement xElement in elements)
         {
            xElement.Remove();
         }
    
         doc.Save("D:\\tst.xml");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-17
      • 1970-01-01
      • 1970-01-01
      • 2014-05-05
      • 1970-01-01
      • 1970-01-01
      • 2020-05-11
      相关资源
      最近更新 更多