gpt4 book ai didi

c# - 从目录结构创建 xml

转载 作者:太空宇宙 更新时间:2023-11-03 18:35:39 25 4
gpt4 key购买 nike

我有一个包含文件的目录和包含文件的子目录,我想从它们创建 xml。这是我的文件夹结构:

C:\inputdata folder contains:
C:\inputdata\file1.txt
C:\inputdata\picture1.jpg
C:\inputdata\subfolder\picture2.jpg
C:\inputdata\subfolder\file2.txt
C:\inputdata\subfolder\anotherfolder \file3.txt
C:\inputdata\anotherfolder\

我想生成这个 xml 文件:

<?xml version="1.0" encoding="UTF-8"?>
<serverfiles>
<file name="picture1.jpg"/>
<file name="file1.txt"/>
<folder name="subfolder">
<file name="picture2.jpg"/>
<file name="file2.txt"/>
<folder name="anotherfolder">
<file name="file3.txt"/>
</folder>
</folder>
<folder name="anotherfolder">
</folder>
</serverfiles>

我已经编写了以下控制台应用程序,但我有两个问题。

  1. 这会生成附加的屏幕截图 xml,它在结构方面与上面的 xml 不完全相同。

  2. 有什么方法可以用我的代码对名称属性进行排序。

有人能给我指出正确的操作方法吗:

    private const string folderLocation = @"c:\inputdata";
static void Main(string[] args)
{
DirectoryInfo dir = new DirectoryInfo(folderLocation);


var doc = new XDocument(CREATEXML(dir));

Console.WriteLine(doc.ToString());

Console.Read();
}

private static XElement CREATEXML(DirectoryInfo dir)
{
//get directories
var xmlInfo = new XElement("serverfiles", new XAttribute("name", dir.Name));

//get all the files first
foreach(var file in dir.GetFiles())
{
xmlInfo.Add(new XElement("file", new XAttribute("name", file.Name)));
}

//get subdirectories
foreach(var subDir in dir.GetDirectories())
{
xmlInfo.Add(CREATEXML(subDir));
}

return xmlInfo;

}

enter image description here

最佳答案

就快完成了:只需对代码进行一些小的修改即可。

    private const string folderLocation = @"c:\inputdata";
static void Main(string[] args)
{
DirectoryInfo dir = new DirectoryInfo(folderLocation);

// makes everything wrapped in an XElement called serverfiles.
// Also a declaration as specified (sorry about the standalone status:
// it's required in the XDeclaration constructor)
var doc = new XDocument(new XDeclaration("1.0", "UTF-8", "yes"),
CREATEXML(dir));

Console.WriteLine(doc.ToString());

Console.Read();
}

private static XElement CREATEXML(DirectoryInfo dir, bool writingServerFiles = true)
{
//get directories
var xmlInfo = new XElement(writingServerFiles ? "serverfiles" : "folder", writingServerFiles ? null : new XAttribute("name", dir.Name)); //fixes your small isue (making the root serverfiles and the rest folder, and serverfiles not having a name XAttribute)

//get all the files first
foreach(var file in dir.GetFiles())
{
xmlInfo.Add(new XElement("file", new XAttribute("name", file.Name)));
}
//get subdirectories
foreach(var subDir in dir.GetDirectories())
{
xmlInfo.Add(CREATEXML(subDir), false);
}
return xmlInfo;

}

关于c# - 从目录结构创建 xml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15981237/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com