Philly
Philly

Reputation: 251

reading repeat xml using xmlnode

I Have XML like

<rss>
<channel>
    <item>
        <category domain="category" nicename="change"><![CDATA[Changing Lives]]></category>
        <category domain="category" nicename="events"><![CDATA[Events]]></category>
        <category domain="category" nicename="leadership"><![CDATA[Leadership]]></category>
        <category domain="category" nicename="spiritual-transformation"><![CDATA[Spiritual Transformation]]></category>
    </item>
    <item></item>
    <item></item>
</channel>
</rss>

I am trying to read category innertext(changing lives, Events, Leadership) ... using foreach condition.. but for every loop I am getting Changing Lives only.. here is my code

    protected void btnImportPost_Click(object sender, EventArgs e)
{

    XmlDocument doc = new XmlDocument();
    string strPath = Server.MapPath("~/App_Data/willowcreekassociationblog.wordpress.xml");
    doc.Load(strPath);
    //Get Channel Node
    XmlNode channelNode = doc.SelectSingleNode("rss/channel");
    if (channelNode != null)
    {
        DateTime temp;
        //Add NameSpace
        XmlNamespaceManager nameSpace = new XmlNamespaceManager(doc.NameTable);
        nameSpace.AddNamespace("excerpt", "http://wordpress.org/export/1.2/excerpt/");
        nameSpace.AddNamespace("content", "http://purl.org/rss/1.0/modules/content/");
        nameSpace.AddNamespace("dc", "http://purl.org/dc/elements/1.1/");
        nameSpace.AddNamespace("wfw", "http://wellformedweb.org/CommentAPI/");
        nameSpace.AddNamespace("wp", "http://wordpress.org/export/1.2/");

        //Parse each item
        foreach (XmlNode itemNode in channelNode.SelectNodes("item"))
        {
            //some code here

            foreach (XmlNode categoryNode in itemNode.SelectNodes("category"))
            {
                //CMS.SiteProvider.CategoryInfo GetCate = null;
                string CategoryName = itemNode.SelectSingleNode("category").InnerText;
                Response.Write(@"<script language='javascript'>alert('root Document:" + CategoryName + "');</script>");

            }

        }
    }
}

Upvotes: 0

Views: 1061

Answers (2)

Rob Levine
Rob Levine

Reputation: 41318

The reason is that you are not writing out the InnerText of itemNode each time round the loop, instead, you are using SelectSingleNode to pull out the first match only.

Try changing your inner loop to:

foreach (XmlNode categoryNode in itemNode.SelectNodes("category"))
{
   //CMS.SiteProvider.CategoryInfo GetCate = null;

   //string CategoryName = itemNode.SelectSingleNode("category").InnerText; // incorrect
   string CategoryName = categoryNode.InnerText;
   Console.Write(CategoryName);
}

Upvotes: 0

Darek
Darek

Reputation: 4797

Just use

string CategoryName = categoryNode.InnerText;

Upvotes: 1

Related Questions