1

I have got below XMLEncode function in VBScript function. I want to write similar function in C# 2.0

Function XMLEncode(byVal stringtoencode)
    Dim strTemp ' As String
    strTemp = stringtoencode
    strTemp = Replace( strTemp, chr(38), "&" )
    strTemp = Replace( strTemp, chr(34), """ )
    strTemp = Replace( strTemp, chr(60), "<" )
    strTemp = Replace( strTemp, chr(62), ">" )
    strTemp = Replace( strTemp, chr(169), "©" )
    XMLEncode = strTemp
End Function

Please suggest!! if there is any in built function in c# or do I need to write same logic in C#

2 Answers 2

1
string xml = "<node>it's my \"node\" & i like it<node>";
using (XmlTextWriter xtw = new XmlTextWriter(@"c:\xmlTest.xml", Encoding.Unicode))
{
    xtw.WriteStartElement("xmlEncodeTest");
    xtw.WriteAttributeString("testAttribute", xml);
    xtw.WriteString(xml);
    xtw.WriteEndElement();
}

// RESULT:
/*
<xmlEncodeTest testAttribute="&lt;node&gt;it's my &quot;node&quot; &amp; i like it&lt;node&gt;">
    &lt;node&gt;it's my "node" &amp; i like it&lt;node&gt;
</xmlEncodeTest>
*/

From This site

Sign up to request clarification or add additional context in comments.

2 Comments

What is this BigMike, I am looking for a function!! I am using .NET 2.0
follow the link, there're are 4 ways to achieve XML Escaping. From the simple way (escaping chars manually via string replaces), to the complex solution (using the XmlTextWriter), passing through some encoding utilis.
1

Look for the HttpServerUtility.HtmlEncode-Method, maybe this can solve your problem.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.