XML deserialization of string elements with newline characters in C #

I can’t understand why this test fails.

Test:

given the following XML:

<?xml version="1.0" encoding="utf-8"?> <foo> <account> 1234567890 </account> <deptCode> ABCXYZ </deptCode> </foo> 

and the following class:

 class Foo { [XmlElement(ElementName = "account", DataType = "normalizedString")] string account; [XmlElement(ElementName = "deptCode", DataType = "normalizedString"] string deptCode; } 

when this XML deserializer:

 XmlSerializer serializer = new XmlSerializer(typeof(Foo)); Foo myFoo = (Foo) serializer.Deserialize(xmlReader); 

I get the following values:

 Foo.account = "\r\n 1234567890 \r\n" Foo.deptCode = "\r\n ABCXYZ \r\n" 

instead of the expected

 Foo.account = "1234567890" Foo.deptCode = "ABCXYZ" 

How can I make the deserialization process give me the expected results? I thought DataType="normalizedString" can do it, but it doesn't seem to work, and when I use XmlReaderSettings.IgnoreWhitespace , it just removes the character "\ r", leaving me with "\ n 1234567890"

+6
source share
3 answers

It seems to be working as intended. From the IgnoreWhitespace documentation:

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

Basically, this is that it preserves (when set to false ) spaces between elements, such as:

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

A new line between <Foo> and <bar> will be returned by the reader. Set IgnoreWhitespace to true and it will not.

To achieve your goal, you will have to perform software cropping, as Cyril mentioned. When you think about this, how should the reader know if the space for the pure string content of the element (as in your examples) is only for indentation or actual content?

To learn more about ignoring spaces, you can look here and.

+4
source

You can create your own XmlTextReader class:

 public class CustomXmlTextReader : XmlTextReader { public CustomXmlTextReader(Stream stream) : base(stream) { } public override string ReadString() { return base.ReadString().Trim(); } } 
+4
source

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

+1
source

Source: https://habr.com/ru/post/899708/


All Articles