Search code examples
asp.net-core.net-corexmlserializer

Dynamic XML element names based on object property value in runtime


Say I have a structure like

    public class Data
    {
        public string ElementName { get; set; }
        public string Content { get; set; }
    }

    public class XmlDoc
    {        
        public List<Data> Elements { get; set; } = new List<Data>(new[] { new Data { ElementName = "A", Content = "CA"}, nnew Data { ElementName = "B", Content = "CB" } })
    }

Is there a way to make the serialized format look like

<XmlDoc>
    <A>CA</CA>
    <B><CB></CB>
<XmlDoc>

?

The gist being that the tag names are generated dynamically from the collection items.


Solution

  • According to your description, I suggest you could try to create XmlDocument and add the element according to your XmlDoc class property.

    More details, you could refer to below codes:

         XmlDoc x1 = new XmlDoc();
            XmlDocument doc = new XmlDocument();
           
            XmlElement root = doc.CreateElement(typeof(XmlDoc).Name);
            foreach (var item in x1.Elements)
            {
                XmlElement newelement = doc.CreateElement(item.ElementName);
                newelement.InnerText = item.Content;
                root.AppendChild(newelement);
    
            }
    
            doc.AppendChild(root);
    
            doc.Save(Console.Out);
    

    Result:

    enter image description here