Fog Creek Software
Discussion Board

Welcome! and rules

Joel on Software

Using XmlDocument.ImportNode() and XmlNodeList

Hey All,

I’m running into this issue with parsing through an xml document by tag name. Below is an example xml document:

File Name: things.xml

As you can see, this xml structure has multiple sublevels. I wish to parse my xml by tag name (example: get elements by tag name “people”, then within here, get elements by tag name “name”). I am trying to access these sublevels via the XmlDocument class in conjunction with the XmlNodeList class. Note the C# code snippet below:

//Create XmlDocument object and load file
XmlDocument l_xmlDocThings = new XmlDocument();

// get node elements based on tag name "people". WORKS
XmlNodeList l_xmlNodePeople = l_xmlDocThings.GetElementsByTagName("people");

// create new xmlDocument and assign it to list of people
XmlDocument l_xmlDocPeople = new XmlDocument();
l_xmlDocPeople.ImportNode(l_xmlNodePeople[0], false);
// Unable to get elements based on tag name "name" because
// innerXML of l_xmlDocPeople is ""
XmlNodeList l_xmlNodeNames = l_xmlDocPeople.GetElementsByTagName("name");

When I retrieve the elements “people”, this works. But when I create a new XmlDocument based on the “people” XmlNodeList[0], I see that I run into issues. The innerXml attribute of l_xmlNodePeople[0] is not imported into l_xmlDocPeople.

What am I doing wrong?

Note: I just wish to access the node structure by tag-name. If you feel there is a better approach to getting elements by tag name, please let me know.


Wednesday, May 04, 2005

Have you tried using "true" for the second parameter of ImportNode? Without checking the docs, I seem to remember this is something along the lines of "deep" or "recursive".

Philipp Schumann
Thursday, May 05, 2005

*  Recent Topics

*  Fog Creek Home