0

I have an object to be serialized using XMLSerializer.serialize(). I have successfully serialize the objects to XML string then write it to file and the file can be read successfully using XmlDocument.load().

But now, a value in object's attribute contains <. The serialize function serializes the object successfully but XMLDocument.load() failed reading the file because the < is found with a wrong format. Is there any function to replace any attribute value in object which contains < or > to &lt; or &gt; without replacing it one by one? Or there is another way to do this?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Darwin Gautalius
  • 317
  • 4
  • 13
  • What's the exact problem you're having? – John Saunders Dec 26 '12 at 05:47
  • 2
    Unlike forum sites, we don't use "Thanks", or "Any help appreciated", or signatures on [so]. See "[Should 'Hi', 'thanks,' taglines, and salutations be removed from posts?](http://meta.stackexchange.com/questions/2950/should-hi-thanks-taglines-and-salutations-be-removed-from-posts). – John Saunders Dec 26 '12 at 05:48
  • Here is an example: I have a node in file like this. `"this < that"` this will produce error because the node contains `<` – Darwin Gautalius Dec 26 '12 at 05:50
  • 1
    That's illegal XML. It must be < – Cole Tobin Dec 26 '12 at 05:51
  • you should put the data in CDATA http://stackoverflow.com/a/2784294/158297 – Amitd Dec 26 '12 at 05:51
  • How did you get that invalid XML to begin with? – John Saunders Dec 26 '12 at 05:52
  • As I said before at the post, I have an object serialized using `XMLSerializer.serialize()`. But one or more attributes sometimes will contain `<`. I know I need to replace it before it is being serialized. But, how can I replace it if the object contains too many attributes to replace. Or is there any other ways to do it without replacing it? – Darwin Gautalius Dec 26 '12 at 05:56
  • Is it possible to show the code sample and the wrong format data? – Amitd Dec 26 '12 at 06:14

2 Answers2

1

XML file generated by XmlSerializer should be valid XML file, or you found a bug in .NET framework (that's very unlikely to happend as this class/method is so popular)

So, please check if there's any chance that the XML file generated has been modified by something else. And if so, you might want to fix the modifier instead of correcting the XML file manually.

Reinhard
  • 100
  • 12
0

Is it possible to use Regex.Replace() to replace special character before it is passed down to be serialize?

Another way would be to use try-catch, and then use a function to replace it when the error is caught. Source: here

Hearty
  • 543
  • 1
  • 5
  • 16