tags:

views:

1466

answers:

5

Hi

My Code:

// Read in Xml-file 
XmlDocument doc = new XmlDocument();
doc.Load("C:/Web.config");

XmlNode d = doc.SelectSingleNode("/configuration");
XmlNode MYNODE = doc.CreateNode("element", "connectionStrings", "");

//newParent.(childNode);
d.AppendChild(MYNODE);

//Saving the document
doc.Save("C:/Web.config");

MyOutput in my Web.config:

<connectionStrings />

The output that i actually want in my Web.config:

<connectionStrings>

</connectionStrings>

What must i change in my code to get the correct output? Also, what must I do if i want my tags to appear just above another tag...Say my --SharePoint-- Tag.

Regards Etienne

+2  A: 

The output is correct. Since you do not have any child elements within the connectionStrings tag, it renders as an empty tag.

<connectionStrings /> means the same thing as <connectionStrings></connectionStrings>.

If you want to insert a tag before a particular node, use the InsertBefore method:

XmlNode sharePoint = doc.SelectSingleNode("SharePoint");
XmlNode MYNODE = doc.CreateNode("element", "connectionStrings", "");

doc.InsertBefore(MYNODE, sharePoint);
Cerebrus
Using the doc.InsertBefore(MYNODE, sharePoint); does not work?
Etienne
+1  A: 

Both the <ConnectionStrings> seems same. There is no difference in <connectionStrings /> and <connectionStrings></connectionStrings>.

You can use AppendChild() or InsertBefore() or InsertAfter() methods to position your nodes.

Anuraj
+1  A: 

You could perhaps add some white-space text into the element?

MYNODE.InnerText = " ";

Or some other content - maybe a comment? Without some content, the two forms are pretty-much identical.

Re the "tag" question - that depends what you mean... but XmlNode has InsertBefore and InsertAfter - just find the node you want it to be adjacent to and use one of those.

Marc Gravell
Thanks for the reply....how would i use the InsertBefore in my code....i tried a few things but keep getting an error.
Etienne
try sharePoint.InsertAfter(MYNODE);
Marc Gravell
Nope, error say: "No overload for method InsertBefore takes '1' arfument
Etienne
Answer : XmlNode root = doc.DocumentElement; root.InsertAfter(connNODE, root.FirstChild);
Etienne
+1  A: 

both of them are well formed xml formats.

but, if you add new childs to your your appended child node, you'll get what you want. For example just add an space into the connectionstrings node :

XmlNode MYNODE = doc.CreateNode("element", "connectionStrings", "");
MYNODE.InnerText = " ";

this will have no effect in actual use of connection strings elements.. but the output will be as you want.

Canavar
Thanks!! Ai stupid me!
Etienne
A: 
XmlNode root = doc.DocumentElement;
root.InsertAfter(connNODE, root.FirstChild);

This is what i needed to do in onder to place my node in the correct spot. Thanks everyone for your help! Etienne

Etienne