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

C# XmlSerialization: Serialize string with attribute

I want to serialize the following from C# classes/structures into xml:

XML sample:

<xml>
   <somename id="bla">content</somename>
</xml>

How can I achieve, that a string has an additional attribute called id?

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

>Solution :

I would use something like this:

/* 
    Licensed under the Apache License, Version 2.0
    
    http://www.apache.org/licenses/LICENSE-2.0
*/
using System;
using System.Xml.Serialization;
using System.Collections.Generic;
namespace Xml2CSharp
{
    [XmlRoot(ElementName="somename")]
    public class Somename {
        [XmlAttribute(AttributeName="id")]
        public string Id { get; set; }
        [XmlText]
        public string Text { get; set; }
    }

    [XmlRoot(ElementName="xml")]
    public class Xml {
        [XmlElement(ElementName="somename")]
        public Somename Somename { get; set; }
    }

}

Actually you can use this tool https://xmltocsharp.azurewebsites.net/

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