使用 c# 追加在 XML 中的特定位置



我有一个这样的XML文件

<?xml version="1.0" encoding="utf-8"?>
<MY_COMPUTER>
<HARDWARE uid="" update="" functions=""  />
<SOFTWARE>
<GAMES uid="" update="" functions=""  url="">
<GAME1 Game1-Attribute1="" />
<GAME2 Game2-Attribute1="" Game2-Attribute2="" Game2-Attribute3="" Game2-Attribute4="" />
<GAME3 Game3-Attribute1="" Game3-Attribute2="" Game3-Attribute3=""/>
<GAME4 Game4-Attribute1="" Game4-Attribute2=""/>
</GAMES>
</SOFTWARE>
</MY_COMPUTER>

我正在尝试将新的软件类型添加到这个 xml 文件中,例如浏览器,浏览器将与游戏相同,它将具有浏览器 1、浏览器 2 和一些浏览器将具有属性。我用过这个

string filePath = "test.xml";
XElement root = XElement.Load(filePath, LoadOptions.PreserveWhitespace);
root.Add(
new XElement("BROWSER",
new XAttribute("uid",""), new XAttribute("update", ""),
new XElement("BROWSER2"),
new XElement("BROWSER3"),
new XElement("BROWSER4"), 
)
);
root.Save(filePath, SaveOptions.DisableFormatting);

但是有了这段代码,它将其附加到软件下,我知道我可能犯了一个非常大的初学者错误,但我无法修复它,有人可以帮助我吗?我也在stackoverflow上检查了很多关于这个问题的问题,但我仍然无法管理它。人们说有很多方法,例如使用 LINQ 或流,我不知道该使用哪一种,但这个文件不会很大,所以我只需要一种可行的方法 谢谢

这个 xml 片段添加到软件元素之后的原因是您将其添加到root元素本身(root.Add)。

如果要将其添加到软件元素中,则应相应地修改代码。

找到所需的元素并改为调用其Add方法。

var softwareElement = root.Descendants("SOFTWARE").First();
softwareElement.Add(
new XElement("BROWSER",
new XAttribute("uid", ""), new XAttribute("update", ""),
new XElement("BROWSER2"),
new XElement("BROWSER3"),
new XElement("BROWSER4")
)
);

然后像以前一样保存所有 xml。

root.Save(filePath, SaveOptions.DisableFormatting);

最新更新