根据目录中XML文件的数量创建多个XmlDocument对象

本文关键字:创建 对象 XmlDocument 文件 XML | 更新日期: 2023-09-27 18:28:11

我在一个目录中有多个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文件的数量创建多个XmlDocument对象

使用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();
            }
        }
    }
}