K
Kim
Im trying to add an element (<Tag>value</Tag>) under a certain child,
but something goes wrong. It gets inserted just before the root end tag
instead of the location I tought it would.
I load an exsisting xml file, so I have the structure. I simply want to
update it.
What am I doing wrong? better ways of inserting elements are
appreciatived.
C# code:
System.Xml.XmlDocument xDoc = new System.Xml.XmlDocument();
xDoc.Load(filename);
System.Xml.XmlNodeList appItems;
System.Xml.XmlNode appItems_child;
System.Xml.XmlElement xElement;
appItems = xDoc.GetElementsByTagName("Folder"); //used in a loop to
determine if an new element should be added
appItems_child = xDoc.DocumentElement;
xElement = xDoc.CreateElement("Folder");
xElement.InnerText = "some string path";
appItems_child.InsertAfter(xElement, appItems_child.LastChild);
XML file input (cut out):
<Configuration>
<Options>
<Settings>
<SourceFolders>
<Folder>C:\</Folder>
<Folder>D:\Test\</Folder>
</SourceFolders>
</Settings>
</Options>
</Configuration>
XML file output (cut out):
<Configuration>
<Options>
<Settings>
<SourceFolders>
<Folder>C:\</Folder>
<Folder>D:\Test\</Folder>
</SourceFolders>
</Settings>
</Options>
<Folder>new path string</Folder> // this is wrong. should have been
under <SourceFolders>
</Configuration>
but something goes wrong. It gets inserted just before the root end tag
instead of the location I tought it would.
I load an exsisting xml file, so I have the structure. I simply want to
update it.
What am I doing wrong? better ways of inserting elements are
appreciatived.
C# code:
System.Xml.XmlDocument xDoc = new System.Xml.XmlDocument();
xDoc.Load(filename);
System.Xml.XmlNodeList appItems;
System.Xml.XmlNode appItems_child;
System.Xml.XmlElement xElement;
appItems = xDoc.GetElementsByTagName("Folder"); //used in a loop to
determine if an new element should be added
appItems_child = xDoc.DocumentElement;
xElement = xDoc.CreateElement("Folder");
xElement.InnerText = "some string path";
appItems_child.InsertAfter(xElement, appItems_child.LastChild);
XML file input (cut out):
<Configuration>
<Options>
<Settings>
<SourceFolders>
<Folder>C:\</Folder>
<Folder>D:\Test\</Folder>
</SourceFolders>
</Settings>
</Options>
</Configuration>
XML file output (cut out):
<Configuration>
<Options>
<Settings>
<SourceFolders>
<Folder>C:\</Folder>
<Folder>D:\Test\</Folder>
</SourceFolders>
</Settings>
</Options>
<Folder>new path string</Folder> // this is wrong. should have been
under <SourceFolders>
</Configuration>