Search code examples
c#xmlxmlserializer

Get names of all child-elements of a node in Xml-Deserialization


I got the following XML-Structure:

<Root>
    <Element Attribute="attibute">
        <ElementINeedNameOf />
        <AnotherElementINeedNameOf />
    </Element>
</Root>

I am trying to read the names of the child-element of element? Therefor I am using System.Xml.Serialization to read the other elements/attributes but I'm unable to read the names of it's child elements.

Thank you.


Solution

  • It is posible by selecting the parent element with XmlAnyElement.

    The following code shows an example solution:

    [XmlAnyElement("Element")]
    public XmlElement Elements{ get; set; }
    
    [XmlIgnore]
    public List<string> ElementNames
    {
        get
        {
            var elementNames = new List<string>();
            if (Elements != null && Elements.HasChildNodes)
            {
                elementNames.AddRange(from XmlNode elementsChildNode in Elements .ChildNodes select elementsChildNode.Name);
                return elementNames ;
            }
            else
            {
                //return empty List
                return tagNames;
            }
        }
    }