Home > Net >  How to serialize an item with an attribute without having child items in C#
How to serialize an item with an attribute without having child items in C#

Time:11-11

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?

CodePudding user response:

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;
}
  • Related