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;
}
}
}
謝謝Ed Plunkett,修復它!非常感激! –