所以我有这个代码构建没有错误,但我需要改变它打开xml文档的方式。现在它可以打开单个xml文档,我需要它做的就是在我的c上打开一个文件夹:并解析文件夹中的所有xml文件。有什么帮助吗?
static void Main(string[] args)
{
XDocument doc = XDocument.Load(@"c:\.cfg"); //Change here
var query = from x in doc.Descendants("X")
select new
{
Max1 = x.Attribute("Max").Value,
Min2 = x.Attribute("Min").Value
};
foreach (var x in query) ;
Console.WriteLine("X");
var query2 = from x in doc.Descendants("Y")
select new
{
Max3 = x.Attribute("Max").Value,
Min4 = x.Attribute("Min").Value
};
foreach (var x in query2)
Console.WriteLine("Y");
var query3 = from x in doc.Descendants("ZA")
select new
{
Max5 = x.Attribute("Max").Value,
Min6 = x.Attribute("Min").Value
};
foreach (var x in query3)
Console.WriteLine("Z");
}
答案 0 :(得分:1)
你应该遍历Directory.EnumerateFiles(@"C:\Something", "*.xml")
。
答案 1 :(得分:0)
......稍微“声明”的方式:
// Program.cs
class Program
{
static void Main(string[] args)
{
const string path = @"C:\stuff";
Parallel.ForEach(Directory.EnumerateFiles(path, "*.xml"), x => Walk(XDocument.Load(x)));
}
static IEnumerable<Calib> MapItem(IEnumerable<XElement> elements)
{
return elements.Select(x => new Calib
{
Max = x.Attribute("Max").Value,
Min = x.Attribute("Min").Value
});
}
static void Walk(XDocument doc)
{
var xitems = MapItem(doc.Descendants("XaxisCalib"));
xitems.Iter(x => Console.WriteLine("(XaxisCalib) X: Min = {0} | Max = {1}", x.Min, x.Max));
var yitems = MapItem(doc.Descendants("YAxisCalib"));
yitems.Iter(x => Console.WriteLine("(YaxisCalib) Y: Min = {0} | Max = {1}", x.Min, x.Max));
var zitems = MapItem(doc.Descendants("ZAxisCalib"));
zitems.Iter(x => Console.WriteLine("(ZaxisCalib) Z: Min = {0} | Max = {1}", x.Min, x.Max));
}
}
// Exts.cs
public static class Exts
{
public static void Iter<T>(this IEnumerable<T> source, Action<T> action)
{
foreach (var item in source)
{
action(item);
}
}
}
// Calib.cs
public class Calib
{
public string Max { get; set; }
public string Min { get; set; }
}
答案 2 :(得分:0)
您可以根据文件中的值创建一个新的Xml文档,然后从中执行任何操作(生成Excel电子表格?),而不仅仅是将值写入控制台:
var fileData = new XElement("root",
from file in New System.IO.DirectoryInfo("C:\Something").GetFiles()
where file.Extension.Equals(".xml", String Comparison.CurrentCultureIgnoreCase)
Let doc = XElement.Load(file.FullName)
select new XElement("File",
new XAttribute("Path", file.FullName),
select new XElement("XAxisCalibs",
from x in doc.Descendants("XAxisCalib")
select new XElement("XAxisCalib",
new XAttribute("Max", x.Attribute("Max").Value),
new XAttribute("Min", x.Attribute("Min").Value)
)
),
select new XElement("YAxisCalibs",
from y in doc.Descendants("YAxisCalib")
select new XElement("YAxisCalib",
new XAttribute("Max", x.Attribute("Max").Value),
new XAttribute("Min", x.Attribute("Min").Value)
)
),
select new XElement("ZAxisCalibs",
from z in doc.Descendants("ZAxisCalib")
select new XElement("ZAxisCalib",
new XAttribute("Max", x.Attribute("Max").Value),
new XAttribute("Min", x.Attribute("Min").Value)
)
)
);
当然,由于这是完整的声明性和一个长语句,如果有必要,调试是一个技巧。