gpt4 book ai didi

c# - 在特定标签中插入元素

转载 作者:太空宇宙 更新时间:2023-11-03 11:46:30 25 4
gpt4 key购买 nike

我试图在我的文件中的特定点插入一个元素,然后将该文件保存出来。但是,我似乎做对了。我的 XML 布局是这样的:

<?xml version="1.0" encoding="utf-8"?>
<Settings>
<Items />
<Users />
</Settings>

这是我当前的代码:

            XDocument xd = XDocument.Load(@"C:\test.xml");

var newPosition = xdoc.Root.Elements("Users");
//I've tried messing around with newPosition methods


XElement newItem = new XElement("User",
new XAttribute("Name", "Test Name"),
new XAttribute("Age", "34"),

);

//how can I insert 'newItem' into the "Users" element tag in the XML file?

xd.Save(new StreamWriter(@"C:\test.xml"));

我想使用 Linq to XML 将“newItem”插入到标记中。感谢您对此的任何帮助。

最佳答案

只需找到 Users 元素并将其附加:

// Note that it's singular - you only want to find one
XElement newPosition = xdoc.Root.Element("User");
XElement newItem = new XElement("User",
new XAttribute("Name", "Test Name"),
new XAttribute("Age", "34"));

// Add the new item to the collection of children
newPosition.Add(newItem);

您对 var 的使用这里让你误入歧途 - 因为 newPosition 的类型在你的代码中确实是 IEnumerable<XElement> ... 你正在寻找 所有 User元素。 (好吧,实际上只有 一个元素,但这无关紧要……它在概念上仍然是一个序列。)

关于c# - 在特定标签中插入元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3292923/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com