[英]Create multiple XmlDocument objects based on the number of XML files in a directory
I have multiple XML files in a directory, Each directory you can consider as each scenario. 我的目录中有多个XML文件,您可以将每个目录视为每种情况。 Based on the business scenario number of XML files may differ in a directory.
根据业务场景,目录中XML文件的数量可能有所不同。
From the Below code I got total number of files. 从下面的代码中,我得到了文件总数。
string tempPath = rootPath+"/Templates"; // Template directory path
DirectoryInfo d = new DirectoryInfo(@tempPath);
FileInfo[] files = d.GetFiles("*.xml"); // getting all file names
Am trying to set the namespace for the xml like the below code 我正在尝试为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/");
}
Later that I trying to insert value in the xml doc like this 后来我试图像这样在xml文档中插入值
XmlNode businessContactNumber = doc.SelectSingleNode(xPath,nsMgr);
The above code is not working and I know am doing some serious mistake in the code. 上面的代码无法正常工作,我知道代码中存在严重错误。 Am new to this C# code, Kindly help me to resolve this issue.
这是C#代码的新手,请帮助我解决此问题。
Using XML Linq 使用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.