3

Say I have the C# code

class Foo
{
    [XmlElement("bar")]
    public string[] bar;
}

var foo = new Foo
{
    bar = new[] { "1", "2", "3" }
};

How do I serialise Foo.bar as <bar>1,2,3</bar>?

4
  • 2
    Use string.Join to fuse the three strings together and then make the bar element be a string not a string[] Commented Aug 12, 2020 at 22:41
  • @Flydog57 if possible, I'd prefer to transform into a single string at time of serialisation Commented Aug 12, 2020 at 22:42
  • 4
    Write custom xml serializer Commented Aug 12, 2020 at 22:43
  • @T.S. okay thank you, I was hoping for a built-in feature Commented Aug 12, 2020 at 22:44

1 Answer 1

6

You need create additional property to serialize array as single element

class Program
{
    static void Main(string[] args)
    {
        var foo = new Foo
        {
            bar = new[] { "1", "2", "3" }
        };
        XmlSerializer serializer = new XmlSerializer(typeof(Foo));
        serializer.Serialize(Console.Out, foo);
    }
}

public class Foo
{
    [XmlIgnore]
    public string[] bar;

    [XmlElement("bar")]
    [EditorBrowsable(EditorBrowsableState.Never)]
    public string BarValue
    {
        get
        {
            if(bar == null)
            {
                return null;
            }
            return string.Join(",", bar);
        }
        set
        {
            if(string.IsNullOrEmpty(value))
            {
                bar = Array.Empty<string>();
            }
            else
            {
                bar = value.Split(",");
            }
        }
    }
}

output:

<Foo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <bar>1,2,3</bar>
</Foo>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.