What is the best way to parse XML using XmlDocument class?

N

Novice

Hi all, I've just finished writing some ASP.NET code that will parse
an xml file and display it to the user. I want to find out whether
I've gone about it the right way.

I've used the XmlDocument class and I pass over the entire structure
grabbing certain nodes, parsing those nodes and then display them on
the webpage. My code does not parse the following xml - but I grabbed
it from the web just now for the sake of example (my actual structure
is MUCH more complex and deep):
<?xml version="1.0" encoding="UTF-8"?>
<family>
<name gender="Male">
<firstname>Tom</firstname>
<lastname>Smith</lastname>
</name>
<name gender="Female">
<firstname>Dale</firstname>
<lastname>Smith</lastname>
</name>
</family>

Now, Let's assume that I'm only interested in displaying nodes that
have the firstname "Tom". By making use of the XmlDocument class I
simply start at the node by using the node method:
SelectNodes("/family/name")

and then using a looping structure I loop through the XML document and
record those nodes that have "Tom" into a DataSet object I've created.

Then once I've finished going through the document, I bind the DataSet
object to a DataGrid object that is on my .aspx page and that is it.

However, once I finished, I realized that there might be a
quicker/(more efficient) way to use the XmlDocument class to get all
of the nodes that match my search criteria without using any looping
structures. In other words, my understanding of the Document Object
Model is that it loads the entire XML structure into memory. Is there
a better way of getting the relevant nodes out of the XmlDocument
object without using code like:
m_nodelist = m_xmld.SelectNodes("/someXMLfile/item")
For Each m_node In m_nodelist
'bunch of conditional code
If (m_innerNode.InnerText = "Tom") Then
For Each m_innerNode In m_node.ChildNodes
'additional parsing
Next
End If
Next

The reason I'm asking is because this XML file will potentially become
VERY large (potentially several megs) and using looping structures
over all of that could end up costing me a lot in terms of run-time.

Thanks,
Novice
 
S

Sharon

using System.Xml.XmlTextReader will give better performance
and using XPath you can query just the data you need
if you have to use code.
but you can simply transform the xml with an xsl document.
Sharon.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top