Reading/Parsing an XML string: code review

G

Gina_Marano

Hey All,

There are many ways to skin a dog (I like cats so no cats) in .Net

I have an XML string in the following format (without linefeeds):

<remoteDir>
<dir>MyDir</dir>
<dir>MyDir2</dir>
<file>
<name>tst2_33520902.txt</name>
<size>11277</size>
<lastModTime m=\"10\" d=\"30\" y=\"2006\" hh=\"10\" mm=\"29\"
ss=\"0\" />
</file>
<file>
<name>tst3_36432046.txt</name>
<size>10897</size>
<lastModTime m=\"10\" d=\"30\" y=\"2006\" hh=\"7\" mm=\"51\"
ss=\"0\" />
</file>
</remoteDir>

i would like to get a list of directories and a list of the files and
attributes.

I have come up with the following. Is there a better way?

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(sFileList);

XmlNodeList filelst = xmlDoc.GetElementsByTagName("file");

for (int i = 0; i < filelst.Count; i++)
{
XmlElement afile = (XmlElement) filelst;
XmlElement afilename =
(XmlElement)afile.GetElementsByTagName("name")[0];
XmlElement afilesize =
(XmlElement)afile.GetElementsByTagName("size")[0];
System.Console.WriteLine(afilename.FirstChild.Value + " " +
afilesize.FirstChild.Value);
}

I would do the same thing to get the list of directories.

Thoughts?

Thanks much!

~Gina~
 
M

Marc Gravell

Depends on size; if not too big, then this should be fine; however, for
large xml you may find XmlReader more efficient - but more complex too.

Marc
 
M

Martin Honnen

Gina_Marano said:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(sFileList);

You can use several APIs to parse out details from XML. In theory an
XmlDocument is only necessary if you do not only want to parse the XML
to read out values but also want to manipulate the XML.
XPathDocument/XPathNavigator suffices to read out values. It should not
matter much however for the simple and short XML that you have shown.
XmlNodeList filelst = xmlDoc.GetElementsByTagName("file");

GetElementsByTagName in .NET has a buggy implementation. Consider using
SelectNodes instead (or SelectSingleNode when you are looking for a
particular node).
<http://support.microsoft.com/kb/823928/en-us>

XmlNodeList filelst = xmlDoc.SelectNodes(@"remoteDir/file");
for (int i = 0; i < filelst.Count; i++)
{
XmlElement afile = (XmlElement) filelst;


foreach (XmlElement afile in filelst) {
XmlElement afilename =
(XmlElement)afile.GetElementsByTagName("name")[0];

Again you could use XPath e.g.
XmlElement afilename = afile.SelectSingleNode("name") as XmlElement;
..NET also allows e.g.
XmlElement afilename = afile["name"];
to access child elements.
afilename.FirstChild.Value

InnerText suffices to read out the text contents e.g.
afilename.InnerText
 

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