http://community.csdn.net/Expert/topic/3091/3091343.xml?temp=.5088159
jiezhi(風依舊) 来了分给他

解决方案 »

  1.   

    察看事例,用第归实现比较简单
    /// <summary>
    /// 将指定目录下的子目录和文件生成xml文档
    /// </summary>
    /// <param name="targetDir">根目录</param>
    /// <returns>返回XmlDocument对象</returns>
    public static XmlDocument CreateXml(string targetDir)
    {
    XmlDocument myDocument = new XmlDocument();
    XmlDeclaration declaration = myDocument.CreateXmlDeclaration("1.0","utf-8",null);
    myDocument.AppendChild(declaration);
    XmlElement rootElement = myDocument.CreateElement(targetDir.Substring(targetDir.LastIndexOf("\\")+1));
    myDocument.AppendChild(rootElement);
    foreach(string fileName in Directory.GetFiles(targetDir))
    {
    XmlElement childElement = myDocument.CreateElement("File");
    childElement.InnerText = fileName.Substring(fileName.LastIndexOf("\\")+1); 
    rootElement.AppendChild(childElement);
    }
    foreach(string directory in  Directory.GetDirectories(targetDir))
    {
    XmlElement childElement = myDocument.CreateElement("Directory");
    childElement.SetAttribute("Name",directory.Substring(directory.LastIndexOf("\\")+1));
    rootElement.AppendChild(childElement);
    CreateBranch(directory,childElement,myDocument);
    }
    return myDocument;
    }
    /// <summary>
    /// 生成Xml分支
    /// </summary>
    /// <param name="targetDir">子目录</param>
    /// <param name="xmlNode">父目录XmlDocument</param>
    /// <param name="myDocument">XmlDocument对象</param>
    private static void CreateBranch(string targetDir,XmlElement xmlNode,XmlDocument myDocument)
    {
    foreach(string fileName in Directory.GetFiles(targetDir))
    {
    XmlElement childElement = myDocument.CreateElement("File");
    childElement.InnerText = fileName.Substring(fileName.LastIndexOf("\\")+1); 
    xmlNode.AppendChild(childElement);
    }
    foreach(string directory in  Directory.GetDirectories(targetDir))
    {
    XmlElement childElement = myDocument.CreateElement("Directory");
    childElement.SetAttribute("Name",directory.Substring(directory.LastIndexOf("\\")+1));
    xmlNode.AppendChild(childElement);
    CreateBranch(directory,childElement,myDocument);
    }
    }