如何使用XDocument动态生成XML文件?

时间:2013-05-17 13:12:12

标签: c# linq-to-xml xsd

正如我在主题中写的那样,我怎么能这样做呢? 请注意,这样的解决方案是不合适的,因为我想通过运行动态创建子节点。

new XDocument(
    new XElement("root", 
        new XElement("someNode", "someValue")    
    )
)
.Save("foo.xml");

我想这第一次就够了,但我会再写一次:

我需要能够在运行时将子节点添加到给定的父节点,在当前语法中我写过这是静态生成的xml,它根本不贡献我,因为所有事先都知道,这不是我的情况。

你将如何使用Xdocument,是吗?

2 个答案:

答案 0 :(得分:9)

如果文档具有已定义的结构并且应填充动态数据,则可以这样:

// Setup base structure:
var doc = new XDocument(root);
var root = new XElement("items");
doc.Add(root);

// Retrieve some runtime data:
var data = new[] { 1, 2, 3, 4, 5 };

// Generate the rest of the document based on runtime data:
root.Add(data.Select(x => new XElement("item", x)));

答案 1 :(得分:5)

非常简单

请相应更新您的代码

XmlDocument xml = new XmlDocument();
XmlElement root = xml.CreateElement("children");
xml.AppendChild(root);

XmlComment comment = xml.CreateComment("Children below...");
root.AppendChild(comment);

for(int i = 1; i < 10; i++)
{
    XmlElement child = xml.CreateElement("child");
    child.SetAttribute("age", i.ToString());
    root.AppendChild(child);
}
string s = xml.OuterXml;
相关问题