I've a XML file like this
<?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>
I'm trying to add new software types into this xml file for example browsers, browser will be same as game, it will have browser1, browser2 and a few of browsers will have attributes. I've used this
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);
but with this code its appending this under SOFTWARE, I know I probably made a really big beginner mistake but I couldn't fix it, can someone help me? I've also checked a lot of questions about this on stackoverflow but I still couldn't manage it. People say there are many ways like using LINQ or stream I don't know which one to use but this file wont be really huge so I just need a way that will work Thanks
The reason of this xml piece adding after software element is that you are adding it to a root
element itself (root.Add
).
If you want to add it inside the software element, you should modify your code accordingly.
Find required element and invoke its Add
method instead.
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")
)
);
Then save all the xml as previously.
root.Save(filePath, SaveOptions.DisableFormatting);