1

Hi all, I have a problem with my xml model. I want to get the child nodes of a parent node and then save the children in a collection. Is there any way to ignore the node "C" and take only the child nodes? I dont want to have a class called "C" with "D" children.

The A node is not the root of my file.

I use the XmlSerializer from Microsoft to deserialize my model.

Thanks in advance!

<A>
    <B>
        <C>
            <D>
                <E/>
            </D>
            <D>
                <E/>
            </D>
        </C>
    </B>
</A>

[XmlRoot("A")]
public class Root
{
    [XmlElement("B")]
    public B BNode {get;set;}
}

public class B 
{
    [XmlArray("C")]
    public D[] DNodes {get;set;}
}
zTim
  • 78
  • 5

1 Answers1

0

Assuming the A node is the document root this should show how to proceed;

    B[] myArray=new B[]{new B("Hello"),new B("World")};
    XmlRootAttribute  root = new XmlRootAttribute ();
    root.ElementName="A";
    XmlSerializer ser = new XmlSerializer(typeof(B[]),root);
    var outStream = new StringWriter();
    ser.Serialize(outStream,myArray);
    var xmlText = outStream.ToString();
    Console.Write(xmlText);
    Console.WriteLine();
    TextReader sr = new StringReader(xmlText);
    B[] result = (B[])ser.Deserialize(sr);

fiddle

For A being child node of some other node use [XmlArray(ElementName="A")] instead of [XmlArrayItem("B")]. fiddle for child node

Taemyr
  • 3,407
  • 16
  • 26