0

I have an xml file and need to extract the InnerXML from a second level child node using C#. Below is a snippet of my XML.

<joblisting:department>Supply</joblisting:department>
<guid isPermaLink="true">https://www.governmentjobs.com/careers/ocso/Jobs/2594527</guid>
<joblisting:categories>
    <joblisting:category xmlns:joblisting="http://www.neogov.com/namespaces/JobListing" xmlns:atom="http://www.w3.org/2005/Atom">
        <CategoryCode>ClericalDataEntry</CategoryCode>
        <Category>Clerical &amp; Data Entry</Category>
    </joblisting:category>
</joblisting:categories>

I need to get the value of the Category element.

I tried using this C# code:

XmlNode t = rssNode.LastChild;
if (t.HasChildNodes)
{
    for (int i = 0; i < t.ChildNodes.Count; i++)
    {
        string xcategory = (t.ChildNodes[i].InnerXml);
        string category = "<category>" + xcategory + "</category>";
        sb.AppendLine(category);
    }
}

but it returns the entire child tree as

<category>
  <CategoryCode>ClericalDataEntry</CategoryCode>
  <Category>Clerical &amp; Data Entry</Category>
</category

All I want to get is is the value from the Category element

How can I drill down to that element only?

Stefan
  • 652
  • 5
  • 19
Perry
  • 1,277
  • 2
  • 17
  • 39

2 Answers2

1

Right now you're taking the entirety of t.ChildNodes[i] and you want just one of its children.

So based on what you have so far, you need to drill down once more if (t.ChildNodes[i].HasChildren) and loop through those, checking for t.ChildNodes[i].ChildNodes[j].Name == "Category" and then get its t.ChildNodes[i].ChildNodes[j].Value.

But that's kind of hacky and you end up with nested loops (if...for...if...for) so you may want to use recursion instead. Alternatively, it might be better to use XmlSerializer and map the data to an object model. Link

mjung
  • 139
  • 7
0

After reading mjung's comments I went a little deeper and was able to come up with a cleaner way to accomplish my goal. I came up with the code below to get my data.

rssSubNode = rssNode.SelectSingleNode("joblisting:categories", nsmgr);
                if (rssSubNode.HasChildNodes)
                {
                    rssSubNode = rssSubNode.SelectSingleNode("joblisting:category", nsmgr);
                    rssSubNode = rssSubNode.SelectSingleNode("Category");
                    string category = rssSubNode.InnerXml;
                    string Category = "<category>" + category + "</category>";
                    sb.AppendLine(Category);
                }
Perry
  • 1,277
  • 2
  • 17
  • 39