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

CSh*_*per 3 c# xsd linq-to-xml

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

new XDocument(
    new XElement("root", 
        new XElement("someNode", "someValue")    
    )
)
.Save("foo.xml");
Run Code Online (Sandbox Code Playgroud)

我想第一次这个很清楚,但我会再写一遍:

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

你会怎么用Xdocument做的,是吗?

小智 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)));
Run Code Online (Sandbox Code Playgroud)

  • 代码的第一行使用`root`,它在第二行声明... (2认同)

Nip*_*tha 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;
Run Code Online (Sandbox Code Playgroud)