-1

I have this Class that I want to convert to an XML Element

public class Person
{
  [XmlElement(ElementName = "PersonName")]
  public string Name { get; set; }
}

This will display an XML

<Person>
  <PersonName>Smith</PersonName>
</Person>

I want to add an attribute to the element PersonName

<Person>
  <PersonName required="true">Smith</PersonName>
</Person>

How would I do that?

JP Dolocanog
  • 451
  • 3
  • 19
  • Does this answer your question? [how to read xml attribute using C# classes using deserialization](https://stackoverflow.com/questions/16632409/how-to-read-xml-attribute-using-c-sharp-classes-using-deserialization) – Jawad May 26 '20 at 23:55

1 Answers1

2

I think you need a special class to hold your Name property, rather than relying on string. Here is an example, using the XmlText and XmlAttribute attributes to control how the built-in XmlSerializer works:

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

namespace SomeNamespace
{
    class Program
    {
        static void Main(string[] args)
        {
            Person me = new Person("me");

            string path = "C:\\temp\\person.xml";
            XmlSerializer serializer = new XmlSerializer(typeof(Person));
            using (StreamWriter sw = new StreamWriter(path))
            {
                serializer.Serialize(sw, me);
            }
        }
    }

    public class Person
    {
        public Person() { } // needed for serialization
        public Person(string name)
        {
            Name = new PersonName(name);
        }

        [XmlElement(ElementName = "PersonName")]
        public PersonName Name { get; set; }
    }

    public class PersonName
    {
        public PersonName() { } // needed for serialization
        public PersonName(string name)
        {
            Name = name;
        }

        [XmlText]
        public string Name { get; set; }

        [XmlAttribute] // serializes as an Attribute
        public bool Required { get; set; } = true;
    }
}

output (at C:\temp\person.xml; you can change Main to serialize to string and print to console if you want):

<?xml version="1.0" encoding="utf-8"?>
<Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <PersonName Required="true">me</PersonName>
</Person>

If you really want your Required attribute to be serialized as the lowercase "required", you can use different properties of XmlAttribute, such as: XmlAttribute(AttributeName = "required")

Sean Skelly
  • 1,229
  • 7
  • 13