我正在尝试将平面XML数据分组到层次结构文件夹中。
下面显示的代码有效。我想找到以下内容:
Console.WriteLine("\t\t{0}
的synatx,
f.Element("FILE_NAME").Value);
f.FileName
之类的using System;
using System.Linq;
using System.Xml.Linq;
namespace TestingStuff
{
class LinqQuestion
{
static void Main(string[] args)
{
Question();
#region End Console
Console.WriteLine();
Console.WriteLine();
Console.WriteLine("*".PadRight(30, '*'));
Console.WriteLine("Done");
#if DEBUG
{
Console.WriteLine("Press any key to exit.");
Console.WriteLine("Where is the any key? --Homer Simpson");
Console.ReadKey(true);
}
#endif
#endregion
}
private static void Question()
{
int count = 0;
XDocument xmlDoc = XDocument.Parse(
@"<ROWSET>
<ROW>
<PARENT_DIR>Parent_100</PARENT_DIR>
<DIR>Folder_110</DIR>
<FILE_NAME>File_111</FILE_NAME>
</ROW>
<ROW>
<PARENT_DIR>Parent_100</PARENT_DIR>
<DIR>Folder_110</DIR>
<FILE_NAME>File_112</FILE_NAME>
</ROW>
<ROW>
<PARENT_DIR>Parent_200</PARENT_DIR>
<DIR>Folder_210</DIR>
<FILE_NAME>File_211</FILE_NAME>
</ROW>
<ROW>
<PARENT_DIR>Parent_200</PARENT_DIR>
<DIR>Folder_220</DIR>
<FILE_NAME>File_221</FILE_NAME>
</ROW>
</ROWSET>");
var rows = from d in xmlDoc.Descendants("ROW")
group d by new
{
ParentDir = d.Element("PARENT_DIR").Value,
Dir = d.Element("DIR").Value
}
;
foreach (var myRow in rows)
{
/*
* Create Folders
* Folder: PARENT_DIR\DIR\FILE_NAME
*
*/
try
{
string[] folders = new string[] { myRow.Key.ParentDir, myRow.Key.Dir };
string newFolder = String.Join("\\", folders);
count++;
Console.WriteLine("{0}\t{1}", count, newFolder);
foreach (var f in myRow)
{
Console.WriteLine("\t\t{0}", f.Element("FILE_NAME").Value);
}
}
catch (Exception ex)
{
Console.WriteLine("Error in Copy Process:");
// Specify the XML details for failed file / row
Console.WriteLine(ex.Message);
}
}
Console.WriteLine();
Console.WriteLine("Total Count: {0}", count);
Console.WriteLine();
Console.WriteLine();
}
}
}
内在的声明。 我目前正在使用4.0版本,但不介意了解制作此版本的新版本的新功能
由于
代码:
{{1}}
答案 0 :(得分:0)
根据SO中的不同post,我设法得到了我需要的东西。
修改后的Linq代码:(仅写入主要部分)
var expr = from d in xmlDoc.Descendants("ROW")
group d by new
{
ParentDir = d.Element("PARENT_DIR").Value,
Dir = d.Element("DIR").Value,
} into gDir
select new
{
GroupKey = gDir.Key,
Data = from z in gDir
select new { FileName = z.Element("FILE_NAME").Value }
};
foreach (var g in expr)
{
Console.WriteLine("{0}\t\t", g.GroupKey.ParentDir, g.GroupKey.Dir);
foreach (var n in g.Data)
Console.WriteLine("\t\t{0}", n.FileName);
}