LINQ to XML(C#)通过节点迭代构建字符串?

时间:2013-06-01 08:40:48

标签: c# xml linq

我会直接切入追逐!

这是我的XML,它包含一个文件夹结构和一个带有md5哈希值的文件列表。

<?xml version="1.0" encoding="utf-8"?>
<dir name="Root">
  <dir name="Folder01">
    <dir name="SubFolder01">
      <file md5="77c34f94b0827a2a511b7c9113fd8e31" name="file01.lua" />
      <file md5="47e656c824a3de6fd6bdf7429045b570" name="file02.lua" />
      <file md5="8c9d3b467fbb3173bebed99bae400995" name="file03.lua" />
      <file md5="ade88ad29426e49c9a81e923bb428445" name="file04.lua" />
    </dir>
    <dir name="SubFolder02">
      <dir name="SubFolder03">
        <dir name="SubFolder04">
          <file md5="e1a8566380b2a4256e1792b48705058c" name="file.png" />
        </dir>
      </dir>
    </dir>
  </dir>
  <dir name="Folder02">
    <dir name="SubFolder01">
      <file md5="12f6a2a9e85817fdf6f791f1b0fe37b3" name="File01.lua" />
    </dir>
  </dir>
</dir>

我想阅读这个XML并生成一个md5这样的文件列表......

Root\Folder01\SubFolder01\file01.lua, 77c34f94b0827a2a511b7c9113fd8e31
Root\Folder01\SubFolder01\file02.lua, 47e656c824a3de6fd6bdf7429045b570
Root\Folder01\SubFolder01\file03.lua, 8c9d3b467fbb3173bebed99bae400995
Root\Folder01\SubFolder01\file04.lua, ade88ad29426e49c9a81e923bb428445
Root\Folder01\SubFolder02\SubFolder03\SubFolder04\file.png, e1a8566380b2a4256e1792b48705058c
Root\Folder02\SubFolder01\File01.lua, 12f6a2a9e85817fdf6f791f1b0fe37b3

这是我到目前为止的(破碎)代码

var SingleFiles = SourceXMLFile.Descendants("dir")

               .Select(x => new
               {
                   FileName = (string)x.Attribute("name"),
                   md5 = (string)x.Attribute("md5")
               });

我意识到我需要遍历节点和后代来构建基于父母等的文件名字符串。但是我现在有点倦怠(尝试了很多方法!)如果有人能帮助我会成为非常感激。

更新:虽然Ron.B.I给出了答案。实际上可能没有答案,它确实让我在正确的方向上推动自己解决问题。

XmlReader rdr = XmlReader.Create(new System.IO.StringReader(XMLasString));
            string newPath = "";
            while (rdr.Read())
            {
                if (rdr.NodeType == XmlNodeType.Element)
                {
                    if (rdr.LocalName == "file")
                        Console.WriteLine(newPath + rdr.GetAttribute(1) + " " + rdr.GetAttribute(0));
                    else
                        newPath = newPath + (rdr.GetAttribute(0)) + Path.DirectorySeparatorChar;
                }
            }

我现在要回答其他问题并标记出“最佳”答案。谢谢你的帮助。

3 个答案:

答案 0 :(得分:3)

var doc = XDocument.Parse(xml);
string[] filesAndMD5 = doc.Descendants("file")
                          .Select(node => GetFullPath(node) + ", " + node.Attribute("md5").Value)
                          .ToArray();                             

filesAndMD5.ForEach(Console.WriteLine);

public string GetFullPath(XElement node)
{
    string res = "";

    while(node != null)
    {
        res = Path.Combine(node.Attribute("name").Value, res);
        node = node.Parent;
    }
    return res;
}

打印:

Root\Folder01\SubFolder01\file01.lua, 77c34f94b0827a2a511b7c9113fd8e31
Root\Folder01\SubFolder01\file02.lua, 47e656c824a3de6fd6bdf7429045b570
Root\Folder01\SubFolder01\file03.lua, 8c9d3b467fbb3173bebed99bae400995
Root\Folder01\SubFolder01\file04.lua, ade88ad29426e49c9a81e923bb428445
Root\Folder01\SubFolder02\SubFolder03\SubFolder04\file.png, e1a8566380b2a4256e1792b48705058c
Root\Folder02\SubFolder01\File01.lua, 12f6a2a9e85817fdf6f791f1b0fe37b3

答案 1 :(得分:1)

var xDoc = XDocument.Parse(xmlstring);
var files = xDoc.Descendants("file")
                .Select(f => String.Format("{0} {1}",
                                            String.Join("/",GetPath(f).Reverse()),
                                            f.Attribute("md5").Value))
                .ToList();


IEnumerable<string> GetPath(XElement e)
{
    while(e!=null) {
        yield return e.Attribute("name").Value;
        e = e.Parent;
    }
}

答案 2 :(得分:0)

略有不同的方法:

using System;
using System.Collections.Generic;
using System.IO;
using System.Xml.Linq;

namespace Demo
{
    class Program
    {
        void run()
        {
            XDocument doc = XDocument.Load("C:\\TEST\\TEST.XML");
            var filenames = ExtractFilenamesAndHashes(doc);
            filenames.Print();
        }

        public IEnumerable<string> ExtractFilenamesAndHashes(XDocument doc)
        {
            return extractFilenamesAndHashes(doc.Root, doc.Root.Attribute("name").Value);
        }

        IEnumerable<string> extractFilenamesAndHashes(XElement root, string path)
        {
            foreach (var folder in root.Elements("dir"))
                foreach (var filename in extractFilenamesAndHashes(folder, Path.Combine(path, folder.Attribute("name").Value)))
                    yield return filename;

            foreach (var file in root.Elements("file"))
                yield return Path.Combine(path, file.Attribute("name").Value + ", " + file.Attribute("md5").Value);
        }

        static void Main()
        {
            new Program().run();
        }
    }

    static class DemoUtil
    {
        public static void Print(this object self)
        {
            Console.WriteLine(self);
        }

        public static void Print(this string self)
        {
            Console.WriteLine(self);
        }

        public static void Print<T>(this IEnumerable<T> self)
        {
            foreach (var item in self)
                Console.WriteLine(item);
        }
    }
}