Search code examples
.netxmlvb.netxps.net-3.5

Is there any built-in function in NET Framework which encodes a string to a valid XML unicode?


After checking an Xps file i noticed that the string within the Xps file <> is converted to &lt;&gt;

So is there any built-in function in the .Net framework that could do this job for me? If it does not exist what characters becides <> should i escape in myOwn function?

I try to implement a search within an xps file, but searching for <> instead of &lt;&gt; returns nothing.

UPDATE: At least i found the list here of xml document escape characters


Solution

  • XMLTextWriter is what you're looking for. You should avoid using any of the HTMLEncode methods (there are several) unless you're actually encoding your text for use in an HTML document. If you're encoding text for use in an XML document (including XHTML), you should use XMLTextWriter.

    Something like this should do the trick:

    StringWriter strWriter = new StringWriter();
    XmlTextWriter xmlWriter = new XmlTextWriter(strWriter);
    xmlWriter.WriteString('Your String Goes here, < and >, as well as other special chars will be properly encoded');
    xmlWriter.Flush();
    
    Console.WriteLine("XML Text: {0}", strWriter.ToString());
    

    See also this other stackoverflow discussion.