Add child to root XElement in XDocument



I am trying to add a node to root element in XML file with XDocument.Load . The problem is that it reapeats the header when I add a new node. Here is the function to create XML file:



private void createDoc()
{
XDocument doc = new XDocument(new XDeclaration("1.0", "UTF-8", "yes"),
new XElement("Items", new XComment("Here will be added new nodes")));
using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
{
if (isoStore.FileExists("positions2.xml"))
{
Debug.WriteLine("File Exists!!!");
isoStore.DeleteFile("positions.xml");
}
else
{
using (IsolatedStorageFileStream isoStream =
new IsolatedStorageFileStream("positions2.xml", FileMode.Create, isoStore))
{
doc.Save(isoStream);
}
}
}
}


From here everything looks fine and the output is ok:



<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Items>
<!--Here will be added new nodes-->
</Items>


To add a child to the root node I use this function:



private void AppendToXMLFile(string reg, string butname, int oldposition, int newposition)
{
using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream("positions2.xml", FileMode.Open, isoStore))
{
XDocument doc = XDocument.Load(isoStream);
var newElement = new XElement("channel",
new XElement("region", reg),
new XElement("name", butname),
new XElement("oldposition", oldposition),
new XElement("newpostions", newposition));
doc.Element("Items").Add(newElement); //add node to root node
doc.Save(isoStream, SaveOptions.OmitDuplicateNamespaces);
}
}
}


And here is the output after the AppendToXMLFile function is called :



<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Items>
<!--Here will be added new nodes-->
</Items><?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Items>
<!--Comment to prevent <Items />-->
<channel>
<region>test</region>
<name>test1</name>
<oldposition>6</oldposition>
<newpostions>0</newpostions>
</channel>
</Items>

No comments:

Post a Comment