user2128702
user2128702

Reputation: 2121

Child nodes of an element in XML

I am trying to write an application that reads each one of the elements but if the element has subelements to read them too.I will give you an example with XML file that I have

XML:

<fci>
    <dog_breeds>

        <dog_breed standart_number="SN207" group="GR9" section="S9.8">
            <name>Пекинез</name>
            <country country_code="CHN" capital="Beijing" official_language="Chinesse" time_zone = "UTC/GMT +8 hours"  currency="Chinese Yuan">
                <country_name>Китай</country_name>
                <country_continent>Азия</country_continent>
                <country_government_type>Комунистически щат</country_government_type>
            </country>
            <year_of_establishment>1904</year_of_establishment>
            <head>
                Голяма, пропорционално по-широка, отколкото дълбока.
                Череп: Широк, широк и плосък между очите; не купловиден; широк между ушите.
                Стоп: Ясно изразен.
            </head>
            <teeth>
                Равни устни, без да се показват зъбите или езика. Здравата долна челюсът е от съществено значение.
            </teeth>
            <ears>
                Със сърцевидна форма, поставени на нивото на черепа, носени плътно по главата и недостигащи под линията на муцуната. Дълъг пищен украсяващ косъм.
            </ears>
            <eyes>
                Големи, ясни, кръгли, тъмни и сияещи. Без видими очни проблеми.
            </eyes>
            <tail>
                Високо поставена, носи се плътно прилепнала, леко извита върху едната от двете страни на гърба. Дълъг украсяващ косъм.
            </tail>
            <colors>
                <primary_color> Всички цветове и петна се допустими и еднакво ценени, с изключение на албинизъм или чевенокафяв цвят</primary_color>
                <secondary_color> Всички цветове и петна се допустими и еднакво ценени, с изключение на албинизъм или чевенокафяв цвят</secondary_color>
                <prefered_color> Всички цветове и петна се допустими и еднакво ценени, с изключение на албинизъм или чевенокафяв цвят</prefered_color>
            </colors>
            <fur>
                Косъм: Козината е дълга, права, с обилна грива, простираща се извън холката, образуваща пелерина около шията. Груб покривен косъм с дебел, по-мек подкосъм. Украсяващ косъм по ушите, задната страна на крайниците, опашката и пръстите.Дължината и количеството на козината не трябва да помрачават очертанията на тялото.
            </fur>
            <image>https://skydrive.live.com/redir?resid=6F26B1E0D6CF648E!291</image>
            <size>
                <males_size>При тази порода единствено теглото се взима под внимание</males_size>
                <females_size></females_size>
            </size>
            <weight>
                <males_weight>5 кг</males_weight>
                <females_weight>5.4 кг</females_weight>
            </weight>
        </dog_breed>
</fci>

As you can see I have elements like country that have subelements(country_name,country_continent,country_government_type) where the actual information stands.So I am trying to read each one of them but it doesn't happen the way I want it to be. Here is my Sample code:

XmlDocument xdoc = new XmlDocument();
xdoc.Load("D:....\\ASP_fifth_xml_file.xml");
XmlNodeList elementsList = xdoc.GetElementsByTagName("country");

    for (int i = 0; i < elementsList.Count; i++)
    {
        foreach (XmlElement element in elementsList[i].ChildNodes)
        {

            richTextOutput_TextBox.Text += element.Name +":"+ element.InnerText+"\n";
            if (element.HasChildNodes)
            {
                foreach (XmlElement subEl in element.ChildNodes)
                {
                    richTextOutput_TextBox.Text += subEl.Name + ":" + subEl.InnerText + "\n";
                }
            }

        }
        richTextOutput_TextBox.Text += "\n \n \n";
    }

When I try to run it it gives me an exception on the line where foreach (XmlElement subEl in element.ChildNodes) stands. It says:

Unable to cast object of type 'System.Xml.XmlText' to type 'System.Xml.XmlElement'.

Upvotes: 3

Views: 1567

Answers (2)

Circle Hsiao
Circle Hsiao

Reputation: 1977

Your ChildNodes include Text Node. If you want to ignore them, use OfType<XmlElement>()

foreach (XmlNode subEl in element.ChildNodes.OfType<XmlElement>()){...}

Upvotes: 0

Prashanth
Prashanth

Reputation: 11

Changing XmlElment to XmlNode will solve the problem. In your case, since you have only one element with a particular tag name, the variable elementsList will be a single node, for loop is not necessary.

        XmlDocument xdoc = new XmlDocument();
        xdoc.Load("D:....\\ASP_fifth_xml_file.xml");
        XmlNode node = xdoc.SelectSingleNode("//country");
        foreach (XmlNode element in node.ChildNodes)
        {
            richTextOutput_TextBox.Text += element.Name + ":" + element.InnerText + "\n";
            if (element.HasChildNodes)
            {
                foreach (XmlNode subEl in element.ChildNodes)
                {
                    richTextOutput_TextBox.Text += subEl.Name + ":" + subEl.InnerText + "\n";
                }
            }

            richTextOutput_TextBox.Text += "\n \n \n";
        }

If the problem still exists try using implicitly typed variable(var).

Upvotes: 1

Related Questions