user2896152
user2896152

Reputation: 816

Insert a RootNode in an XML using C# XmlDocument

I have a string in XML format returned by a without RootNode as follows:

<Node1 Id = "1" Value = "a"/>
<Node2 Id = "2" Value = "b"/>
<Node3 Id = "3" Value = "c"/>

Now, what I want is to embed the returned string in a root node, for example

<XML>
   <Node1 .... />
   <Node2 .... />
</XML>

how can I do this using System.Xml namespace (XmlDocument, ecc..) ?

I have following code:

XmlDocument xml = new XmlDocument(); 
xml.Loadxml(stringWithoutRoot); 

Thank you in advance.

EDIT: ok sorry I was unclear. My real problem is this. I have a lot of methods doing practically the same thing, the only thing that changes is the name of the stored procedure that must be executed. So what I want to do to make the code more readable is to create only one method and pass the name of the stored procedure as its input parameter. I think this is more logic.

Second issue: I noticed that some stored procedures return an xml with root node and others don't so my solution is to pass also the XML as input parameter.

An example invoking,

executeSqlCommand(mySP, "<XML></XML>)

will put the result of the stored procedure in the XML as follows

<XML>resultFromSPWithoutRootNode</XML>

so I need something like this

string result = ..... // some operation in DB

if (!string.IsNullOrEmpty(rootXMl))   // where rootXML is my second parameter
{
    append the result to the root node rootXML
}

The append way is missing.

Upvotes: 0

Views: 158

Answers (2)

user2896152
user2896152

Reputation: 816

I will try to use XmlDocumentFragment like suggested here:

Append XML string block to existing XmlDocument

Thank you

Upvotes: 0

J&#233;r&#244;me
J&#233;r&#244;me

Reputation: 149

maybe something like that ?

XmlDocument xml = new XmlDocument();
string nodesString = "<node/>" ;
xml.LoadXml("<root>" + nodesString+ "</root>");

Upvotes: 1

Related Questions