XML:如何从 IEnumerable 对象中删除元素
本文关键字:对象 删除 元素 IEnumerable XML | 更新日期: 2023-09-27 18:30:59
我使用 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>
如果"操作日期"子节点没有退出,我想删除"操作"节点。
生成 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"节点,但正如我所说,它可以创建,也可以不能创建。
选择所有没有ActionDate
元素的元素(即它是空的),并将它们从动作元素中删除:
actions.Elements("Action")
.Where(a => a.Element("ActionDate") == null)
.Remove();
顺便说一句,如果您正在生成 XML,请考虑不要添加此类元素。这比添加和删除要好。
我再举一个例子:
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");