views:

46

answers:

2

Hi! I have a simple xml file like this one:

<xml>
  <check>
    <a>b&lt;</a>
    <b>
      <test>asdf</test>
    </b>
    <test>jj&amp;j</test>
    </check>
</xml>

I would like to "double escape" all special chars so it will result in &amp;lt; and &amp;amp; with a simple linq to xml statement. The xml should still be valid, only the values need to be escaped. Anyone knows a solution for this?

The resulting xml should look like this:

<xml>
  <check>
    <a>b&amp;lt;</a>
    <b>
      <test>asdf</test>
    </b>
    <test>jj&amp;amp;j</test>
    </check>
</xml>

Thanks in advance

+1  A: 

If you know that you only have encoded entities in the text nodes, you could simply replace every instance of & with &amp;.

Though why you would even need to do such a thing escapes me.

Oded
I have to do it because we have a webservice that needs all input double escaped, because it first generates a temporary xml (first encoding) that gets processed later(second encoding, still needs to be valid). So thats the need for double escaping.
FireFart
+1  A: 

You can't have & in the name of an element, attribute, or declaration so the only possible place for it is in the values (text nodes and attribute values). Since this is precisely where you say you want to do this replace, then a simple blind replace is the way to go. Whether you should use string.Replace() or a streaming method depends on usage and the size of the entire body.

I agree with everyone else, this smells bad.

Jon Hanna