I am trying to use HttpUtility.HtmlEncode() to encode special characters in the xml reponse document in c# if a node has empty string as node attribute value. Here is my code for encoding as it fails when any xml node has empty attribute.

public static string EncodeResponseXML(string responseXML)
        {
            string pattern = "(?<=>)(?<content>[^>]+)(?=<)|(?<start>\")(?<content>.+?)(?<end>\")";
            string result = Regex.Replace(responseXML, pattern, m =>
                        m.Groups["start"].Value +
                        HttpUtility.HtmlEncode(HttpUtility.HtmlDecode(m.Groups["content"].Value)) +
                        m.Groups["end"].Value);
            responseXML = result;
            return responseXML;
        }

Here is my sample xml to be encoded:

<Coverage>
<Type>Terrorism</Type>
<Deductible type=\"Total\" value=\"0\"/>
<Limit type=\"Total\" value=\"\"/>
<Premium>0</Premium>
<PolicyLevelCoverage>1</PolicyLevelCoverage>
<PerClaimOrOccurrenceLimit/>
<PerClaimDeductible/>
<TermAggregateLimit>
</Coverage>

Encoded xml is like this :

<Coverage>

    <Type>Terrorism</Type>

    <Deductible type="Total" value="0"/>

    <Limit type="Total" value="&quot; /&gt;&lt;Premium&gt;0&lt;/Premium&gt;&lt;PolicyLevelCoverage&gt;1&lt;/PolicyLevelCoverage&gt;&lt;PerClaimOrOccurrenceLimit&gt;&lt;/PerClaimOrOccurrenceLimit&gt;&lt;PerClaimDeductible&gt;&lt;/PerClaimDeductible&gt;&lt;TermAggregateLimit&gt;&lt;/TermAggregateLimit&gt;

Here the value attribute of Limit node is blank and that's the reason it is unable to encode properly`

0

There are 0 best solutions below