Brad Jarrett Brad Jarrett - 6 months ago 22
C# Question

Writing advertising XML from directory read using linq C#

I am trying to write a directory into an advertising file for AdRotator to read.

The XML file should look like this:

<?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>


However when I try to add the tag, I cannot get an opening an closing tag. Also, I cannot get the
ImageUrl
formatted correctly - I only get this:

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


Here is my code:

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;
}
}
}

Answer Source

xmlInfo.Add(new XElement("Ad")); creates and adds the Ad element. You then throw it away without giving it any children. You want to add the ImageUrl element as a child of Ad, not of xmlInfo:

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

You have another problem: You can't add attributes with empty names. Since you don't need one, that's fine. Just set the content of ImageUrl to file.Name. I've fixed that too.