Iterating through elements of XML file

M

Mike P

I have an XML file (see below) and I need to be able to iterate through
the different folder objects so that I can get at the source,
destination etc and create a folder object from each of them. I have
tried to use a foreach like this...foreach (XmlElement el in
xmlDoc)..but I just get errors. Any ideas how to do this?

<?xml version="1.0" encoding="utf-8" ?>
<folders>
<folder>
<source>\\lpt0224\c$\testfolder</source>
<destination>\\slnapp02\c$\testfolder</destination>
<frequency>daily</frequency>
<backupbeforedelete>5</backupbeforedelete>
<backedup>0</backedup>
<lastbackup>22/10/2008</lastbackup>
</folder>
<folder>
<source>\\lpt0224\c$\testfolder2</source>
<destination>\\slnapp02\c$\testfolder2</destination>
<frequency>weekly</frequency>
<backupbeforedelete>2</backupbeforedelete>
<backedup>1</backedup>
<lastbackup>22/10/2008</lastbackup>
</folder>
</folders>
 
M

Marc Gravell

Something like below? Note that deserialization (i.e. XmlSerializer)
would be another simple option - just run "xsd.exe" against your xml
fragment (to get an xsd), then again against the xsd (with the /classes
option) to get suitable C# classes.

Marc

XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
foreach (XmlElement folder in
doc.SelectNodes("/folders/folder"))
{
string source =
folder.SelectSingleNode("source").InnerText;
Console.WriteLine(source);
}
 
M

Mike P

Marc,

This is the method that I used :

XmlElement root = xmlDoc.DocumentElement;

//iterate through elements
foreach (XmlElement el in root)
{
XmlNode nodeSource = el.SelectSingleNode(".//source");

etc
}

Is this an equally valid way to go about this?

Thanks,

Mike
 
M

Marc Gravell

If the root contains anything other than folders, it will have different
results. The ".//source" will check more than just the immediate
descendents, which again could (if the xml changes) break things.

So it will give the same result *now*, but is a bit more brittle.

Marc
 

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