1 year ago
#289750

Craig
C# How to load XML from sql Xml data type in to another XmlDocument without it converting < to &lt; etc
Good afternoon,
Whilst there are seemingly many answers to this particular question, none of them seem to be working for me, and i'm unsure just exactly where my problem lies.
Problem - My newly created XML output file has escaped "<" to & lt; How can it remain as it is? I understand the parser is doing what it should but its not what i want.
Using C#, I am trying to take some data from SQL, in the form of xml type, load it into XmlDocument and save it to a file. Except the SQL content has been escaped and is therefore different to whats in the output file.
So lets say I grab my SQL xml data and populate it in to XmlDocument like:-
XmlDocument newXML = new XmlDocument();
newXML.loadXml("<root><Output>Craig</Output></root>);
I then create an Output file instance like so:-
//Create output file, root etc
XmlDocument xmlOutputDoc = new XmlDocument();` //new instance
//declaration
XmlDeclaration xmlDeclaration = xmlOutputDoc.CreateXmlDeclaration("1.0", "UTF-8", null);
//xml declaration
XmlElement root = xmlOutputDoc.DocumentElement;` //root creation
xmlOutputDoc.InsertBefore(xmlDeclaration, root);
//create root element and attribute namespaces
XmlElement RootElement = xmlOutputDoc.CreateElement(string.Empty, "root", string.Empty);
xmlOutputDoc.AppendChild(RootElement);
I then add newXML.OuterXml to my output document xmlOutputDoc like this:-
//create Output location element
XmlElement Output = xmlOutputDoc.CreateElement("Output", string.Empty);
RootElement .AppendChild(Output);
XmlText OutputValue = xmlOutputDoc.CreateTextNode(newXML.OuterXml);
Output .AppendChild(OutputValue );
So, this generates an XML file with the following:-
& lt;root& gt;& lt;Output& gt;Craig& lt;/Output& gt;& lt;/root& gt;
Whereas I want it to retain:-
<root><Output>Craig</Output></root>
I have tried to recreate a new string and replace these characters from & lt; back to "<". Ive tried using the WebUtility reference. Tried adding / specifying the declaration to UTF-8.
I dont understand which part of the process is doing the change, is it XmlDocument.Save? Could i try using the XMLWriter and using the WriteRaw?
Best I've done is wrap the xml contents in to a CDATA tag and that retains what i need, I just dont want/need the CDATA tags there?
Any help is greatly appreciated.
Thanks
c#
xml
xmldocument
0 Answers
Your Answer