Arrays and folders

  • Thread starter Thread starter Trond Hoiberg
  • Start date Start date
T

Trond Hoiberg

I have an XML file with some data:

<Directlist>
<Directory>
<ID>1</ID>
<name>DirectoryRed</name>
</Directory>
<Directory>
<ID>2</ID>
<name>DirectoryBlue</name>
</Directory>
<Directory>
<ID>3</ID>
<name>DirectoryWhite</name>
</Directory>
</Directlist>

Is there a way i can read only the <name> (DirectoryRed, DirectoryBlue,
DirectoryWhite) into an array and then generate Folders using a method like
this (example):

public static void CreateDirectory(string directory)
{
string path = directory;
try
{
if (!Directory.Exists(path))
{
// Create the directory it does not exist.
Directory.CreateDirectory(path);
}
}
catch (Exception e)
{
MessageBox.Show("Creating directory failed: {0}", e.ToString());
}
finally {}
}

THe result will be 3 new folders
best regards
Trond
 
Hi Trond

Use XPath

XmlDocument doc = new XmlDocument();
doc.Load(<your XML in some form>);
XmlNodeList nodes = doc.SelectNodes("//name/text()");
foreach( XmlNode node in nodes)
{
if( !Directory.Exists(node.Value)
{
Directory.CreateDirectory(node.Value);
}
}

Regards

Richard Blewett - DevelopMentor
http://staff.develop.com/richardb/weblog

I have an XML file with some data:

<Directlist>
<Directory>
<ID>1</ID>
<name>DirectoryRed</name>
</Directory>
<Directory>
<ID>2</ID>
<name>DirectoryBlue</name>
</Directory>
<Directory>
<ID>3</ID>
<name>DirectoryWhite</name>
</Directory>
</Directlist>

Is there a way i can read only the <name> (DirectoryRed, DirectoryBlue,
DirectoryWhite) into an array and then generate Folders
 
Thank you wery much. XPath is new to me but i see now that i should spend
some time learning it. You saved me a lot of time now :-)
Best regards
Trond
 
Yep, XPath is definitely thre most efficient (in terms of the amount of code you have to write) way of getting data out of an XmlDocument. But you have to be happy to take the hit (which for small documents isn't a big deal) to load the document into memory. For big documents you may have to drop down to using XmlReader but in most situations it isn't necessary.

One last thing, Xpath is *very* xml namespace sensitive. If the document you showed isn't exactly like the document you are processing (like there is a default namespace or something) then you have more work to do.

Regards

Richard Blewett - DevelopMentor
http://staff.develop.com/richardb/weblog

nntp://news.microsoft.com/microsoft.public.dotnet.languages.csharp/<[email protected]>

Thank you wery much. XPath is new to me but i see now that i should spend
some time learning it. You saved me a lot of time now :-)
Best regards
Trond
 
Back
Top