I'm trying to insert an element at a specific point within my file, then save that file out. However, I can't seem to get it right. My XML layout is like this:
<?xml version="1.0" encoding="utf-8"?>
<Settings>
<Items />
<Users />
</Settings>
This is my current code:
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"));
I'd like to use Linq to XML to开发者_如何学运维 insert 'newItem' into the tag. Thanks for any help on this.
Just find the Users element, and append it:
// 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);
Your use of var
here was leading you astray - because the type of newPosition
in your code was really IEnumerable<XElement>
... you were finding all the User
elements. (Okay, there would only have actually been one element, but that's irrelevant... it was still conceptually a sequence.)
精彩评论