![](/img/trans.png)
[英]Loading multiple xml files with c# XmlDocument leading to memory leakage
[英]Create multiple XmlDocument objects based on the number of XML files in a directory
我的目錄中有多個XML文件,您可以將每個目錄視為每種情況。 根據業務場景,目錄中XML文件的數量可能有所不同。
從下面的代碼中,我得到了文件總數。
string tempPath = rootPath+"/Templates"; // Template directory path
DirectoryInfo d = new DirectoryInfo(@tempPath);
FileInfo[] files = d.GetFiles("*.xml"); // getting all file names
我正在嘗試為xml設置名稱空間,如以下代碼所示
//Setting namespace for each xml
foreach(FileInfo file in files)
{
var tempXml = file.Name;
XmlDocument tempXml = new XmlDocument();
tempXml.Load(tempPath+"/"+file.Name);
XmlNamespaceManager nsMgr = new XmlNamespaceManager(tempXml.NameTable);
nsMgr.AddNamespace("imp", namespace1); // namespace1 value I took it from excel
nsMgr.AddNamespace("soapenv", "http://schemas.xmlsoap.org/soap/envelope/");
}
后來我試圖像這樣在xml文檔中插入值
XmlNode businessContactNumber = doc.SelectSingleNode(xPath,nsMgr);
上面的代碼無法正常工作,我知道代碼中存在嚴重錯誤。 這是C#代碼的新手,請幫助我解決此問題。
使用XML Linq
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.IO;
namespace ConsoleApplication62
{
class Program
{
const string FOLDER = @"\c:\temp";
static void Main(string[] args)
{
string[] filenames = Directory.GetFiles(FOLDER);
foreach (string file in filenames)
{
XDocument tempXml = XDocument.Load(file);
XElement root = (XElement)tempXml.FirstNode;
XNamespace nsMgr = root.Name.Namespace;
XElement node = root.Descendants(nsMgr + "TagName").FirstOrDefault();
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.