Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[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?

>Solution :

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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading