使用Linq删除XML文档的各个部分

时间:2011-10-16 15:53:56

标签: c# linq-to-xml

我如何使用Linq删除其元素包含{}参数的所有部分?在我的示例中,我想删除{SecName1}

部分

来源文件:

<ReceiptLayoutMaintenanceRequest>
  <ReceiptLayoutName>Test Layout1</ReceiptLayoutName> 
  <ActionName>Add</ActionName> 
 <ReceiptLayoutForMaintenance>
  <Name>Test Layout1</Name> 
  <Description>ReciptDesc</Description> 
  <PrinterName>Emulator - Receipt</PrinterName> 
  <ReceiptLayout>
    <Name>AAA</Name> 
    <Description>$</Description> 
    <TemplateName>DefaultTemplate</TemplateName> 
    <LayoutParameters /> 
  </ReceiptLayout>
  <ReceiptLayout>
    <Name>{SecName1}</Name> 
    <Description>$</Description> 
    <TemplateName>DefaultTemplate</TemplateName> 
    <LayoutParameters /> 
  </ReceiptLayout>
 </ReceiptLayoutForMaintenance>
</ReceiptLayoutMaintenanceRequest>

通缉输出

<ReceiptLayoutMaintenanceRequest>
  <ReceiptLayoutName>Test Layout1</ReceiptLayoutName> 
  <ActionName>Add</ActionName> 
 <ReceiptLayoutForMaintenance>
  <Name>AAA</Name> 
  <Description>ReciptDesc</Description> 
  <PrinterName>Emulator - Receipt</PrinterName> 
  <ReceiptLayout>
    <Name>AAA</Name> 
    <Description>$</Description> 
    <TemplateName>DefaultTemplate</TemplateName> 
    <LayoutParameters /> 
  </ReceiptLayout>
 </ReceiptLayoutForMaintenance>

感谢

3 个答案:

答案 0 :(得分:2)

这将删除任何具有子ReceiptLayout的{​​{1}}节点,该节点以括号开头和结尾并生成所需的输出:

Name

这可以简化为一个Linq语句,我个人更喜欢将Linq查询和修改(删除)分开:

XDocument doc = XDocument.Load(@"test.xml"); //load xml
var nodesToRemove = doc.Descendants("ReceiptLayout")
                       .Where(x => x.Element("Name").Value.StartsWith("{") 
                                && x.Element("Name").Value.EndsWith("}"))
                       .ToList();

foreach (var node in nodesToRemove)
    node.Remove();

答案 1 :(得分:1)

var doc =  XDocument.Parse(xml);
doc.Descendants()
   .Where(n => !n.HasElements  && Regex.IsMatch(n.Value, "[{].*?[}]"))
   .Select(n=>n.Parent) // because you want to remove the section not the node
   .Remove();
xml = doc.ToString();

答案 2 :(得分:1)

使用let关键字

的BrokenGlass代码变体
var doc = XDocument.Load(@"test.xml");

var list = from p in doc.Descendants("ReceiptLayout")
           let q = p.Element("Name")
           let r = q != null ? q.Value : string.Empty
           where r.StartsWith("{") && r.EndsWith("}")
           select p;

list.Remove();

这是“过早优化”:-)我“缓存”p.Element("Name").Value。啊......我检查是否真的有一个Name元素,这样如果没有一个,一切都不会崩溃: - )