Personally I'd suggest using LINQ to XML. It's a much easier API to use than XmlDocument
.
But yes, if you want to modify an existing document then typically using an in-memory representation is simpler than using a streaming API. It's possible to do the latter of course, but it's not easy.
Here's an example to create the same XML as you've already got (other than the declaration: any reason you'd want to use Latin-1 instead of something like UTF-8 which can represent the whole of Unicode, btw?)
var doc = new XDocument(
new XElement("MyParts",
new XElement("parts",
new XElement("item", "Part1"),
new XElement("color", "Red"),
new XElement("size", "SM")),
new XElement("parts",
new XElement("item", "Part2"),
new XElement("color", "Blue"),
new XElement("size", "XXL"))));
Then if you wanted to add another part:
doc.Root.Add(
new XElement("parts",
new XElement("item", "Part3"),
new XElement("color", "Green"),
new XElement("size", "L")));
Admittedly I'd expect you'd want to encapsulate the "create a parts element" bit into a method to avoid repeating it all the time... but hopefully you get the picture.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…