使用linq C#从目录中编写广告XML

时间:2017-05-08 19:53:10

标签: c# xml linq

我正在尝试将目录写入广告文件以供AdRotator阅读。

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 个答案:

答案 0 :(得分: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即可。我也解决了这个问题。