Domanda

I dynamically generate XML file using XElement class. The sequence of interest looks as following:

<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>

I want to remove "Action" node if "ActionDate" child node doesn't exit.

The code that generates XML file looks as following:

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

The CreateSeanceElement method creates "ActionDate" node, but as I've said it could or couldn't be created.

È stato utile?

Soluzione

Select all elements which do not have ActionDate element (i.e. it is null) and remove them from actions element:

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

BTW if you are generating XML, consider not to add such elements. It's better than add and remove.

Altri suggerimenti

i'll give you another example:

     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");
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top