簡體   English   中英

在同一文件夾中處理多個XML文件,並使用c#保存它們

[英]Process multiple XML files in the same folder and save them using c#

我試圖從一個文件夾中的多個XML文件中提取soap:Body的內容。 它適用於單個文件,如下所示:

XmlNamespaceManager mgr = new XmlNamespaceManager(doc.NameTable);
mgr.AddNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/");
doc.LoadXml(doc.DocumentElement.SelectSingleNode("soap:Body", mgr).ChildNodes[0].OuterXml);
doc.Save(@"E:\new.xml");

要對多個文件執行相同的操作,請使用以下代碼:

XmlDocument xDoc = new XmlDocument();
string path = @"C:\Folder";
foreach (string file in Directory.EnumerateFiles(path, "*.xml"))
{
    xDoc.Load(Path.Combine(Directory.GetCurrentDirectory(), file));
    XmlNamespaceManager mgr = new XmlNamespaceManager(xDoc.NameTable);
    mgr.AddNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/");
    xDoc.LoadXml(xDoc.DocumentElement.SelectSingleNode("soap:Body", mgr).ChildNodes[0].OuterXml);

}

處理后如何保存文件?

那么這樣的事情呢:

XmlDocument xDoc = new XmlDocument();
string path = @"C:\Folder";
foreach (string file in Directory.EnumerateFiles(path, "*.xml"))
{
   xDoc.Load(Path.Combine(Directory.GetCurrentDirectory(), file));
   XmlNamespaceManager mgr = new XmlNamespaceManager(xDoc.NameTable);
   mgr.AddNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/");
   xDoc.LoadXml(xDoc.DocumentElement.SelectSingleNode("soap:Body", mgr).ChildNodes[0].OuterXml);
   doc.Save("E:\\" + file);
}

問候,

編輯:我想我明白你的要求。

您要遍歷某個文件夾中的每個文檔,然后要在對另一個文件夾進行一些編輯后保存每個文件?

您可以在foreach循環中添加一些變量作為計數器,並像這樣使用Save()方法(這樣,每個文件都會以新名稱保存):

doc.Save(string.Format(@"E:\new{0}.xml", counter);
++counter; // new number for next file

或者,您可以使用TaiT的答案並使用與原始文件相同的名稱保存每個文件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM