36

I'm new into XML Serialization using .NET and after working with it for some time I'm quite fuzzled now. I can serialize elements with attributes containing other elements but how can I serialize something like

<myElement name="foo">bar</myElement>

I use a class for myElement with a XmlAttribute for the "name", but how to refer the value of the XML Element?

Thanks in advance.

0

1 Answer 1

81

[XmlText], like so:

using System;
using System.Xml.Serialization;
[Serializable, XmlRoot("myElement")]
public class MyType {
    [XmlAttribute("name")]
    public string Name {get;set;}

    [XmlText]
    public string Text {get;set;}
} 
static class Program {
    static void Main() {
        new XmlSerializer(typeof(MyType)).Serialize(Console.Out,
            new MyType { Name = "foo", Text = "bar" });
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

6 years later and it just solved my problem also:). Thanks Marc!
XmlSerializer throws a Reflection exception if MyType is a property.
@Suncat2000 if you're seeing something unexpected, an example (maybe on "gist.github.com") would really help

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.