2013-04-14 52 views
2

我有我想讀一個XML文件,並輸出它的數據我的XML是象下面這樣:讀取XML沒有返回

<?xml version="1.0" encoding="UTF-8"?> 
<serverfiles> 
    <file name="picture1.jpg"/> 
    <file name="file1.txt"/> 
    <folder name="subfolder"> 
     <file name="picture2.jpg"/> 
     <file name="file2.txt"/> 
     <folder name="anotherfolder"> 
      <file name="file3.txt"/> 
     </folder> 
    </folder> 
    <folder name="anotherfolder"/>  
</serverfiles> 

而想要輸出它是這樣:

picture1.jpg 
file1.txt 
subfolder\picture2.jpg 
subfolder\file2.txt 
subfolder\anotherfolder\file3.txt 

我試過這個:

string xml = new WebClient().DownloadString(""); 
XmlDocument xdoc = new XmlDocument(); 
xdoc.LoadXml(xml); 

XmlElement element = xdoc.DocumentElement; 

XmlAttributeCollection attr_coll = element.Attributes; 

for(int i = 0; i < attr_coll.Count; i++) 
{ 
    string attr_name = attr_coll[i].Name; 
} 

但是在for循環計數我沒有得到任何東西可以有人請幫助我。

+0

Ar你是否表示你沒有看到任何輸出? –

+0

這不會工作,你必須循環throgh每個節點snd尋找每個節點的屬性 – Rafa

回答

1

您也可以使用X-路徑:

 foreach (XmlNode file in xdoc.SelectNodes("//file")) 
     { 
      string filename = file.Attributes["name"].Value; 

      foreach (XmlNode folder in file.SelectNodes("./ancestor::folder")) 
      { 
       string foldername = folder.Attributes["name"].Value; 
       filename = foldername + "\\" + filename; 
      } 
      System.Diagnostics.Debug.WriteLine(filename); 
     } 

此代碼示例適用於您的XML。

祝你好運與你的追求。

+0

什麼是//文件?它是我的XML的位置? – James

+0

「文件」是有趣標記的標記名。 xml中任何位置的文件標籤的x路徑都是「//文件」。請參閱Google XPath的教程。 – Casperah

0

你必須使用遞歸獲得想要的結果。我認爲它會使用LINQ to XML簡單:

遞歸函數

public static IEnumerable<string> GetFiles(XElement source, string currentPath = "") 
{ 
    foreach (var file in source.Elements("file")) 
    { 
     yield return currentPath + (string)file.Attribute("name"); 
    } 
    foreach (var folder in source.Elements("folder")) 
    { 
     foreach (var file in GetFiles(folder, currentPath + (string)folder.Attribute("name") + "/")) 
      yield return file; 
    } 
} 

使用

using System.Xml.Linq; 

(...) 

var doc = XDocument.Load("Input.txt"); 
var files = GetFiles(doc.Root).ToList(); 
-1

這LINQ到XML應該這樣做,沒有循環,這樣也許有點更高效

XDocument document = XDocument.Load("c:\\tmp\\test.xml"); 
    var files = from i in document.Descendants("file") 
       where i.Attribute("name") != null 
       select new 
        { 
         Filename = (i.Parent != null && i.Parent.Name == "folder" ? 
             (i.Parent.Parent != null && i.Parent.Parent.Name== "folder" ? 
             i.Parent.Parent.Attribute("name").Value + @"\" + i.Parent.Attribute("name").Value + @"\" + i.Attribute("name").Value : 
             i.Parent.Attribute("name").Value + @"\" + i.Attribute("name").Value): 
             i.Attribute("name").Value) 

        }; 
+0

您的查詢返回不正確的結果。不返回完整的文件夾路徑,只有最後一個+文件名。 – MarcinJuraszek

+0

沒有看到第二級,很確定有些想法可以解決這個問題,不過很快會編輯我的答案。 Downvote可能有點過早:) – James

+0

當你的答案被修復時,我將刪除我的downvote。現在只要記住,該文件可以深得多,然後2個級別的文件夾:) – MarcinJuraszek