简体   繁体   中英

C# XmlSerializer trim whitespaces

I've trouble trimming strings when using the XmlSerializer , when using a XmlReader. The IgnoreWhitespace option shows no effect and the element string still contains \\n and whitespaces.

Is there any way to trim it "on the fly"? I would prefer such a method since I deserialize into an array of strings

Here's an example xml:

<?xml version='1.0' encoding='UTF-8'?>
<root>
  <element>
    some random string
  </element>
  <element>
    another random string
  </element>
</root>"

And here's the example code:

class Program
    {
        public static void Main(string[] args)
        {
            string xml =
            @"<?xml version='1.0' encoding='UTF-8'?>
            <root>
              <element>
                 some random string
              </element>
                <element>
                 another random string
              </element>
            </root>";

            var string_reader = new StringReader(xml);

            var xml_reader = XmlReader.Create(string_reader, new XmlReaderSettings()
            {
                IgnoreWhitespace = true //setting this option doesn't work
            });
            root d = (root)new XmlSerializer(typeof(root)).Deserialize(xml_reader);
            d.elements[0].Contains("\n"); //true

            //Dispose string/xml reader

            Console.Read();
        }
    }

    public class root
    { 
        [XmlElement(ElementName ="element")]
        public string[] elements { set; get; }
    }

After reading in the XML file, you need to manually trim out the whitespace

root d = (root)new XmlSerializer(typeof(root)).Deserialize(xml_reader);
for (int i = 0; i < d.elements.Count; i++)
{
  d.elements[i] = d.elements[i].Replace("\n", String.Empty).Trim();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM