我正试图将一项统一的XML数据归为等级夹。
如下文所示代码。 我正试图找到以下办法:
- How can I change the synatx for
Console.WriteLine(" {0}
,f.Element("FILE_NAME").Value);
to something likef.FileName
in the inner foreach statement. - Is there anything else I can do to make it more efficient and/or readable?
我目前正在4年左右,但想想到的是,新版本的新特点使这种信条变得更形。
成就
法典:
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_DIRDIRFILE_NAME
*
*/
try
{
string[] folders = new string[] { myRow.Key.ParentDir, myRow.Key.Dir };
string newFolder = String.Join("\", folders);
count++;
Console.WriteLine("{0} {1}", count, newFolder);
foreach (var f in myRow)
{
Console.WriteLine(" {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();
}
}
}