[英]XDocument XElement Constructor
我正在尝试构建一个动态XDoc,其中包含工具用作“路径”的文件夹列表。 每个“文件夹”元素都是树中的另一层
例:
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是我在代码中之前填充的一个List。 但是我在生产线方面有问题:
XElement folderPath = new XElement();
什么是实现XElement的好方法,以便我可以动态添加FolderList中包含的文件夹? 我收到的错误是“ System.Xml.Linq.XElement不包含采用0个参数的构造函数”。
XElement类中no parameter-less constructor
,您应该像这样初始化它
XElement xFolderPath = new XElement("FolderPath");
它接受字符串,因为它可以implicitly
转换为XName
解决问题的另一种技巧是定义xFolderPath
对象实例
XElement
没有无参数的构造函数。 您要使用的构造函数需要一个XName来分配给XElement,并且您还可以选择传递该XElement
的内容。
您可以在下面的代码中看到创建XElement
folderPath变量的地方,我使用的是XElement(XName name, params object[] content)
,您在其中传递了XElement
的名称,在这种情况下,我正在传递XAttribute
对象的数组作为其内容。
在那之后,我创建了一个名为previousNode的临时XElement
对象,并为其分配了folderPath对象。
在for循环中,我正在使用XElement(XName name)
构造函数创建一个名为newNode的新XElement
,并将其作为内容添加到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 = "contact@email.com";
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;
}
}
}
}
<L0 fromDate="2015-03-23T16:13:52.6702528-05:00"
toDate="2015-03-23T16:13:52.6702528-05:00"
contactName="ContactName"
email="contact@email.com">
<L1>
<L2 />
</L1>
</L0>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.