2014-04-03 44 views
1

我正在嘗試構建一個動態XDoc,其中包含一個工具用作「路徑」的文件夾列表。每個 「文件夾」 元件是在樹另一層XDocument XElement構造函數

實施例:

Root Level 

-- Folder L0 

     -- Folder L1 

     -- Folder L2 

這是在XML表示如下:

<FolderPath> 
    <Folder>L0</Folder> 
    <Folder>L1</Folder> 
    <Folder>L2</Folder> 
</FolderPath> 

我的代碼如下:

 // Build up the innermost folders inside the Folderpath element dynamically   
     XElement folderPath = new XElement(); 
     folderPath.Add(new XElement(FolderList[0], 
      new XAttribute("fromDate", FromDate), 
      //attributes for Folder w/ lots of attributes 
      new XAttribute("toDate", ToDate), 
      new XAttribute("contactName", ContactName), 
      new XAttribute("email", Email), 
      FolderList[0])); 

     for (int i = 1; i < FolderList.Count; i++) 
     { 
      folderPath.Add(new XElement(FolderList[i])); 
     } 

FolderList是我在代碼中的這一點之前填充的列表。但是我有問題,與線路:

XElement folderPath = new XElement(); 

什麼是落實的XElement,這樣我可以動態地添加包含在FolderList文件夾的好方法?我得到的錯誤是「System.Xml.Linq.XElement不包含一個構造函數,它接受0個參數」。

+0

這幾乎是一歲,但我碰到它,同時尋找一些答案的XElement,你仍然需要任何幫助?如果你有一個你想要得到的XML看起來如何的例子,我可以找出一些可行的方法。 – Zack

回答

1

有在的XElement類no parameter-less constructor你應該初始化像這樣的例子

XElement xFolderPath = new XElement("FolderPath"); 

它接受字符串,因爲它可以implicitly轉換爲XName

克服自己的問題,另一個棘手的方式來定義xFolderPath對象實例

+0

不錯的@JulieShannon。 – gleng

0

XElement沒有無參數構造函數。您想要使用的構造函數需要將XName分配給XElement,並且可以選擇傳遞該內容以及XElement

您可以在下面創建XElement FOLDERPATH變量,其中,我使用的是XElement(XName name, params object[] content),在那裏你通過XElement的名稱,在這種情況下,我路過XAttribute對象的數組作爲代碼見它的內容。

之後,我創建了一個名爲previousNode的臨時對象XElement,併爲其指定了folderPath對象。

在for循環中,我創建與XElement(XName name)構造一個新的名爲XElement newNode,並將其添加爲內容的previousNode XElement,然後設置previousNode爲新創建的newNode,所以任何額外的元素將被添加作爲XElement的孩子,創建我假設你想要的層次結構,它顯示在代碼示例下面。

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

namespace CommandLineProgram 
{ 
    public class DefaultProgram 
    { 
     public static void Main(string[] args) 
     { 
      List<String> FolderList = new List<string>() { "L0", "L1", "L2" }; 
      DateTime FromDate = DateTime.Now; 
      DateTime ToDate = DateTime.Now; 
      String ContactName = "ContactName"; 
      String Email = "[email protected]"; 

      XElement folderPath = new XElement(FolderList[0], 
       new XAttribute("fromDate", FromDate), 
       //attributes for Folder w/ lots of attributes 
       new XAttribute("toDate", ToDate), 
       new XAttribute("contactName", ContactName), 
       new XAttribute("email", Email)); 

      XElement previousNode = folderPath; 
      for (int i = 1; i < FolderList.Count; i++) 
      { 
       XElement newNode = new XElement(FolderList[i]); 
       previousNode.Add(newNode); 
       previousNode = newNode; 
      } 
     } 
    } 
} 

folderPath.ToString()輸出

<L0 fromDate="2015-03-23T16:13:52.6702528-05:00" 
    toDate="2015-03-23T16:13:52.6702528-05:00" 
    contactName="ContactName" 
    email="[email protected]"> 
    <L1> 
    <L2 /> 
    </L1> 
</L0>