简体   繁体   中英

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.

maybe something like that ?

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

I will try to use XmlDocumentFragment like suggested here:

Append XML string block to existing XmlDocument

Thank you

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM