繁体   English   中英

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

[英]Writing advertising XML from directory read using linq C#

我正在尝试将目录写入广告文件中,以供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;
        }
    }
}

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 我也解决了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM