阅读xml&创建目录C#

时间:2013-06-04 11:08:33

标签: xml directory

<City title="CityOne">
  <Companies title="Comp1">
    <Company>A</Company>
    <Company>P</Company>
    <Company>R</Company>
  </Companies>
  <Companies title="Comp2">
    <Company>D</Company>
    <Company>F</Company>
    <Company>H</Company>
  </Companies>
</City>

首先创建文件夹CityOne然后在那两个文件夹Comp1&amp; COMP2。然后在它们各自的文件夹A,P,R(在Comp1下)D,F,H(在Comp2下)。

请让我知道如何在C#

中做同样的事情

1 个答案:

答案 0 :(得分:1)

 string Rootpath = "C:\\MyFolder";
 string xml = "<City title='CityOne'>"
                     + "<Companies title='Comp1'>"
                     + "<Company>A</Company>"
                     + "<Company>P</Company>"
                     + "<Company>R</Company>"
                     + "</Companies>"
                     + "<Companies title='Comp2'>"
                     + "<Company>D</Company>"
                     + "<Company>F</Company>"
                     + "<Company>H</Company>"
                     + "</Companies>"
                     + "</City>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);

XmlNodeList xmlFolderCity = doc.SelectNodes("//City");
for (int counter1 = 0; counter1 < xmlFolderCity.Count; counter1++)
{
    string CityFolder = xmlFolderCity[counter1].Attributes["title"].InnerText;
    if (!System.IO.Directory.Exists(Rootpath + "\\" + CityFolder))
    {
        System.IO.Directory.CreateDirectory(Rootpath + "\\" + CityFolder);
    }

    XmlNodeList xmlCompanyGroup = xmlFolderCity[counter1].SelectNodes("//Companies");
    for (int counter2 = 0; counter2 < xmlCompanyGroup.Count; counter2++)
    {
        string CompanyGroupFolder = xmlCompanyGroup[counter2].Attributes["title"].InnerText;
        if (!System.IO.Directory.Exists(Rootpath + "\\" + CityFolder + "\\" + CompanyGroupFolder))
        {
             System.IO.Directory.CreateDirectory(Rootpath + "\\" + CityFolder + "\\" + CompanyGroupFolder);
        }

        XmlNodeList xmlCompany = xmlCompanyGroup[counter2].ChildNodes;
        for (int counter3 = 0; counter3 < xmlCompany.Count; counter3++)
        {
             string CompanyFolder = xmlCompany[counter3].InnerText;
             if (!System.IO.Directory.Exists(Rootpath + "\\" + CityFolder + "\\" + CompanyGroupFolder + "\\" + CompanyFolder))
            {
                System.IO.Directory.CreateDirectory(Rootpath + "\\" + CityFolder + "\\" + CompanyGroupFolder + "\\" + CompanyFolder);
            }

        }
    }
}