XML Serialization XmlTextAttribute and Arrays

CSharp · Console

/Program.cs

using System;
using System.Diagnostics;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

public class Program
{
	public static void Main()
	{
		// Arrange
		// XML taken from https://github.com/dotnet/runtime/blob/main/src/libraries/System.Private.Xml/tests/XmlSchema/TestFiles/StandardTests/xsd10/simpleType/bug102159_1.xml
        var bug102159_1 = """
                          <?xml version="1.0"?>
                          <root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="bug102159_1.xsd">
                            <nms>a b c d</nms>
                            <mylist>a b c d</mylist>
                          </root>
                          """;
		var serializer = new XmlSerializer(typeof(Root));

		// Act
		var instance = (Root)serializer.Deserialize(new StringReader(bug102159_1))!;
			
		// Assert
		if (instance.Nms.Items.Length != 4) throw new InvalidOperationException($"Property Nms contains {instance.Nms.Items.Length} elements.");
		if (instance.MyList.Items.Length != 4) throw new InvalidOperationException($"Property MyList contains {instance.MyList.Items.Length} elements.");
	}
}

[XmlRootAttribute("root")]
public class Root
{
    [XmlElement("nms")]
    public Nms Nms { get; set; }
    
    [XmlElement("mylist")]
    public MyList MyList { get; set; }
}

public class Nms
{
    [XmlText]
    public string[] Items { get; set; }
}

public class MyList
{
    [XmlText]
    public string[] Items { get; set; }
}
;