Thanks alot, it works very well.
"Morten Wennevik" <Mo************@hotmail.comwrote in message
news:op.tnx7maidklbvpo@stone...
Hi Alan
The code below assumes xml contains the original xml data and will add a
node under the files node
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
XmlNode fileNode = doc.CreateNode(XmlNodeType.Element, "file",
doc.NamespaceURI);
XmlNode nameNode = doc.CreateNode(XmlNodeType.Element, "name",
doc.NamespaceURI);
XmlNode locationNode = doc.CreateNode(XmlNodeType.Element, "location",
doc.NamespaceURI);
nameNode.InnerText = "editor.exe";
locationNode.InnerText = @"C:\executable";
fileNode.AppendChild(nameNode);
fileNode.AppendChild(locationNode);
doc["files"].AppendChild(fileNode);
If you have a separate method creating the xml nodes you can rewrite it to
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
XmlNode node = doc["files"].AppendChild(CreateElement("file", "", doc));
node.AppendChild(CreateElement("name", "editor.exe", doc));
node.AppendChild(CreateElement("location", @"C:\executable", doc));
....
private XmlNode CreateElement(string name, string value, XmlDocument doc)
{
XmlNode node = doc.CreateNode(XmlNodeType.Element, name, doc.NamespaceURI);
node.InnerText = value;
return node;
}
The trick is to position yourself before adding any data to select a node
you can do
XmlNode node = doc["files"];
or
XmlNode node = doc.SelectSingleNode("files");
The last way is useful if for instance you want to get all the file nodes
XmlNodeList list = doc.SelectNodes("files/file");
On Sun, 18 Feb 2007 12:54:13 +0100, Alan T <al*************@yahoo.com.au>
wrote:
I used
XmlDocument to load from a file.
Then how do I append an element to the end?
<files>
<file>
<name>graphic.txt</name>
<location>c:\temp</location>
</file>
</files>
I want to add this:
<file>
<name>editor.exe</name>
<location>c:\executable</location>
</file>
--
Happy coding!
Morten Wennevik [C# MVP]