0

I am trying to generate this simplified xml snippet below.

<?xml version="1.0" encoding="utf-16"?>
<group>
  <name attr="yes">My name</name>
</group>

When I serialize the below code the attribute goes to the group but I want the attribute to go to the name.

// C# class
[XmlRoot("group", IsNullable = false)]
public class Test1
{

    [XmlAttribute]
    public string attr = "yes";
    [XmlElement("name")]
    public string Name;
}
// Output
<?xml version="1.0" encoding="utf-16"?>
<group attr="yes">
  <name>My name</name>
</group>

If I make the element name a class I can get the attribute in the right place, however, now I get an additional nested element name.

[XmlRoot("group", IsNullable = false)]
public class Test1
{

    [XmlElement("name")]
    public Test2 Name;
}

public class Test2 : Object
{
    [XmlAttribute]
    public string attr = "yes";

    [XmlElement("name")]
    public string Name;
}
// Output
<group>
  <name attr="yes">
    <name>My name</name>
  </name>
</group>

Question is how can I get the attribute on my element name without having child items to the element?

uncletall
  • 6,609
  • 1
  • 27
  • 52
  • [Is this what you are looking for?](https://stackoverflow.com/questions/11330643/serialize-property-as-xml-attribute-in-element) – ShubhamWagh Nov 11 '22 at 12:09
  • If your name has attributes, it surely is some kind of a nested type, isn't it. So you cannot provide an attribute to some simple value. You can provide attributes only to classes, thus `name` should be its own class as well. From a class-view there's no difference between attributes and properties/fields. – MakePeaceGreatAgain Nov 11 '22 at 12:11
  • This is what I see in you link I would like some more text – uncletall Nov 11 '22 at 12:14

1 Answers1

1

You'll have to mark that Name property on Test2 with an XmlText instead of an XmlElement.

public class Test2
{
    [XmlAttribute]
    public string attr = "yes";

    [XmlText]
    public string Name;
}
pfx
  • 20,323
  • 43
  • 37
  • 57
  • Brilliant, that works. @MakePeaceGreatAgain, I didn't mind the extra class. I just wanted the avoid the inner element – uncletall Nov 11 '22 at 12:19
  • 1
    @MakePeaceGreatAgain I've read `without having child items to the element?` as xml child items. – pfx Nov 11 '22 at 12:20
  • That's right, I didn't want child items in the xml.. I just need to conform to an existing file format – uncletall Nov 11 '22 at 12:21