XML Deserialization of string elements with newlines in C#

后端 未结 3 463
迷失自我
迷失自我 2021-02-06 08:42

I can\'t seem to figure out why this test doesn\'t pass

The test is:

given the following XML:


           


        
相关标签:
3条回答
  • 2021-02-06 09:14

    Try using XmlTextReader for deserialization with the WhiteSpaceHandling property set to WhiteSpaceHandling.None and Normalization = true

    0 讨论(0)
  • 2021-02-06 09:16

    You can create custom XmlTextReader class:

    public class CustomXmlTextReader : XmlTextReader
    {
        public CustomXmlTextReader(Stream stream) : base(stream) { }
    
        public override string ReadString()
        {
            return base.ReadString().Trim();
        }
    }
    
    0 讨论(0)
  • 2021-02-06 09:23

    It seems it is working as intended. From IgnoreWhitespace documentation:

    White space that is not considered to be significant includes spaces, tabs, and blank lines used to set apart the markup for greater readability.

    Basically, what it does is preserves (when set to false) whitespaces in between elements such as:

    <Foo>
    
    <bar>Text</bar>
    </Foo>
    

    The newline between <Foo> and <bar> will be returned by reader. Set IgnoreWhitespace to true, and it won't.

    To achieve your goal you'll have to do programmatic trimming, as mentioned by Kirill. When you think about it, how is reader supposed to know whether whitespace of pure string content of element (as in your examples) is just for indenting purposes or actual content?

    For more reading on ignoring whitespaces you may want to take a look here and here.

    0 讨论(0)
提交回复
热议问题