2

I am trying to use the value of <Directory> in my following piece of code:

 Public Function GetFile() As String
    Dim di As New DirectoryInfo(< Directory >)
    Dim files As FileSystemInfo() = di.GetFileSystemInfos()
    Dim newestFile = files.OrderByDescending(Function(f) f.CreationTime).First
    Return newestFile.FullName
End Function

Is there any way i can call the value stored in the xml file in my code?

1
  • Which XML file are you talking about? Commented Feb 22, 2012 at 23:45

3 Answers 3

4

Andy's answer is good, but in VB it's even easier.

Dim xmlDoc As XDocument
Dim dir as String
xmlDoc = XDocument.Load("XMLFile1.xml")
dir = xmlDoc.<ServerList>.<Server>.<Directory>.First().Value;

Or even easier if the XML file will never have more than one <Directory> element that you care about:

dir = xmlDoc...<Directory>.First().Value;

To answer your comment on Andy's answer:

dir = (From server as XElement in xmlDoc...<Server>
      Where server.<ServerName>.First().Value = requiredServer
      Select server.<Directory>.First().Value)(0);
Sign up to request clarification or add additional context in comments.

2 Comments

Could i use this code in a similar way if i wanted to populate an asp drop-down-list with the server names in the xml file?
Absolutely - From server as XElement in xmlDoc...<Server> Select server.<ServerName>.First().Value will give you an IEnumerable(Of String) containing the server names.
3

As you are clearly familiar with Linq, you can operate on the Xml using System.Xml.Linq.

Apologies, this is in c#.

var xDoc = XDocument.Load("XMLFile1.xml");
var dir = xDoc.Element("ServerList").Elements("Server").Elements("Directory").First().Value;

If you have the Xml stored in a string replace XDocument.Load with XDocument.Parse.

Obviously you'll have to defend against parse errors, file missing and schema inconsistencies in your production code.

2 Comments

Thanks for the answer, works perfectly. However, if i allowed the user to select what server they wanted, and wrote their choice to a variable, how would i select the correct xml node then?
Add a where clause, similar to this var dir = xDoc.Element("ServerList").Elements("Server").Where(svr => svr.Element("ServerName").Value == "T2").Elements("Directory").First().Value;
1

You can use this http://support.microsoft.com/kb/301225

1 Comment

Linq to XML is MUCH easier than this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.