Groups | Blog | Home
all groups > dotnet xml > march 2006 >

dotnet xml : Assigning XML string as the content of an attribute


McGeeky
3/10/2006 2:46:58 PM
Hi. I want to assign an XML string to an XML attribute. This XML string must
undergo "escape" conversion so that the < and & symbols are converted in to
escaped equivalents.

Does the .Net library have a conversion method that does this? Note that I
want to construct the resulting XML string myself without having to use an
XmlDocument.

E.g.

string myXml = "<root><record/><record/></root>";

string myDoc = "<doc myXml='" + Converter.escapeMyXml (myXml ) + "'/>";

--
McGeeky
http://mcgeeky.blogspot.com


McGeeky
3/10/2006 3:27:39 PM
Thanks for that! Its really helped.

The reason for the XML in the attribute is that I am passing it as a
parameter to a stored procedure which then uses openxml to read from it.

--
McGeeky
http://mcgeeky.blogspot.com


[quoted text, click to view]

Martin Honnen
3/10/2006 4:13:41 PM


[quoted text, click to view]


[quoted text, click to view]

Sure, you should always use XmlTextWriter if you want to construct/write
some XML, here is a simple example:

string myXml = "<root><record/><record/></root>";

StringWriter stringWriter = new StringWriter();
XmlTextWriter xmlWriter = new XmlTextWriter(stringWriter);

xmlWriter.WriteStartElement("doc");
xmlWriter.WriteAttributeString("myXml", myXml);
xmlWriter.WriteEndElement();
xmlWriter.Flush();
xmlWriter.Close();

string xml = stringWriter.ToString();

Console.WriteLine("XML created is:\r\n{0}", xml);

Result then is e.g.

<doc myXml="&lt;root&gt;&lt;record/&gt;&lt;record/&gt;&lt;/root&gt;" />


So .NET provides all what you need. Only I have doubts that putting XML
escaped into an attribute is usually a good idea as that way it loses
its structure and is plain text for any XML tool.

--

Martin Honnen --- MVP XML
AddThis Social Bookmark Button