Xml 文件读取

时间:2023-12-11 23:01:44

.NET 读取Xml文件,用到XmlDocument类。

1、要获取文档的根: DocumentElement

2、Attributes :获取 XmlAttributeCollection 包含此节点的属性。 (主体操作都是获取属性值)

  DirectoryInfo dir = new DirectoryInfo(@"D:\XXX\XML"); //文件夹路径
FileInfo[] fileInfo = dir.GetFiles();
Dictionary<string, List<string>> tabDic = new Dictionary<string, List<string>>();
foreach (FileInfo item in fileInfo)
{
string path = item.DirectoryName + "\\" + item.Name;
XmlDocument doc = new XmlDocument();
doc.Load(path);
XmlNode root = doc.DocumentElement; //根节点
XmlNodeList nodes = root.SelectNodes("ormTable");
foreach (XmlNode node in nodes)
{
string tableName = node.Attributes["tableName"].Value; //获取表名
List<string> lstField = new List<string>(); //文件字段长度>0的字段列表
XmlNodeList fieldsNode = node.SelectNodes("Field"); //各个字段
foreach (XmlNode fnode in fieldsNode)
{
//文件字段长度大于0,加入列表
if (fnode.Attributes["filePath"].Value.Length > )
{
lstField.Add(fnode.Attributes["fieldName"].Value);
}
}
if (lstField.Count > )
{
//表名不在字典中
if (!tabDic.ContainsKey(tableName))
{
tabDic.Add(tableName, lstField);
}
}
}
}

读取文件夹中所有Xml文件