首页 > 解决方案 > 使用 c# 删除 XML Header 和 Footer 节点

问题描述

我有我试图自动化的控制台应用程序,有手动过程从 .trg 文件中删除页眉和页脚标签。任何人都可以建议如何使用 c sharp 删除页眉和页脚。

标题看起来像这样。

<Batch remotefolder="\\srv-dg-procl13\nexdox\nxtil04\process\200863-142325x-mkts\output\archive\absamples_pims_pdf\" grid="200863-142325X-MKTS" streamID="ABSAMPLES_PIMS_PDF" delivertobox="False">
  <Application application="NXTIL04" name="Mifid 10 percent drop Notification " output="ABSAMPLES_PIMS_PDF">
    <Indexes>
      <Index name="Reference" description="Reference" type="StringDefinition" visible="True" />
    </Indexes>
  </Application>

页脚看起来像这样。

</Batch> 

这就是我想要做但不工作的事情。

private void RemoveHeader(string Xlfile)
        {
            XmlDocument doc = new XmlDocument();

            doc.Load(Xlfile);

            foreach (XmlNode node in doc.SelectSingleNode("Batch"))
            {
                doc.RemoveAll();
            }
        }

标签: c#xml

解决方案


XPath 是您的朋友。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

    namespace testconsole
    {
            class Program
            {
                    public static string strFileName = "c:\\temp\\test.xml";
                    static void Main(string[] args) {
                            XmlDocument xml = new XmlDocument();
                            xml.Load(strFileName);

                            XmlElement ndMatch = (XmlElement)xml.SelectSingleNode("//Application");

                            if (ndMatch != null) {
                                    XmlDocument xmlNew = new XmlDocument();
                                    xmlNew.LoadXml(ndMatch.OuterXml);
                                    xmlNew.Save(strFileName + ".new");
                            } else {
                                    Console.Write("Cannot load " + strFileName);
                            }
                    }
            }
    }

推荐阅读