2017-05-08 44 views
0

我正在嘗試將目錄寫入廣告文件以供AdRotator閱讀。從使用linq讀取的目錄中寫入廣告XML C#

XML文件應該是這樣的:

<?xml version="1.0" encoding="utf-8" ?> 
<Advertisements> 
    <Ad> 
    <ImageUrl>\002222_BMPs\Pic1.bmp</ImageUrl> 
    </Ad> 
    <Ad> 
    <ImageUrl>\002222_BMPs\Pic2.bmp</ImageUrl> 
    </Ad> 
    <Ad> 
    <ImageUrl>\002222_BMPs\Pic3.bmp</ImageUrl> 
    </Ad> 
    </Advertisements> 

然而,當我嘗試添加標籤,我不能開口的結束標記。此外,我不能讓格式化ImageUrl正確 - 我只得到這樣的:

<Advertisements> 
    <ad /> 
    <ImageUrl>\002222_BMPs\Pic3.bmp> 
    <ad /> 
    <ImageUrl>\002222_BMPs\Pic3.bmp> 
    <ad /> 
    <ImageUrl \002222_BMPs\Pic3.bmp> 
</Advertisements> 

這裏是我的代碼:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Xml.Linq; 
using System.IO; 

namespace ConsoleApplication1 
{ 
    class Program 
    { 
     private const string folderLocation = @"c:\002222"; 

     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 ? "Advertisements" : "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("Ad")); 
        xmlInfo.Add(new XElement("ImageUrl", new XAttribute("", 
file.Name))); 
       } 

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

      return xmlInfo; 
     } 
    } 
} 

回答

1

xmlInfo.Add(new XElement("Ad"));創建並添加Ad元素。然後你把它扔掉而不給它任何孩子。你想在ImageUrl元素添加爲Ad一個孩子,不xmlInfo

var ad = new XElement("Ad"); 
ad.Add(new XElement("ImageUrl", file.Name)); 
xmlInfo.Add(ad); 

你有另外一個問題:你不能用空的名字添加屬性。既然你不需要一個,那很好。只需將ImageUrl的內容設置爲file.Name即可。我也修正了這一點。

+0

謝謝Ed Plunkett,修復它!非常感激! –