C# XML SelectNodes function
This is my first post and I have am concerned that some might think I have bothered trying to solve the problem myself, so forgive m开发者_运维技巧e if I rant on. I am currently trying to develop a set of functions for importing an xml document and creating a basic object from it.
Currently I have this code looking for all xml files in a directory and displaying the file names in a listbox. Overall there's about 10,000 xml files so it take a while to load.
public void CreateLibrary()
{
List<string> fixtureList = new List<String>();
string[] dirs = Directory.GetFiles(@"C:\Windows.old\Users\Michael\Desktop\Application_ DEV\XMLData", "*.xml",
SearchOption.AllDirectories);
foreach (string dir in dirs)
{
string fixture = System.IO.Path.GetFileName(dir);
lbxLibrary.Items.Add(fixture);
}
What I would like to happen is when the user selects a new listbox item, the url for the file is passed to a GetData function. see below:
selection change event
private void lbxLibrary_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
{
Fixture fixture = new Fixture();
lblFixtureName.Text = fixture.GetModelName("C:\Windows.old\Users\Michael\Desktop\Application_ DEV\XMLData\\ExampleData.xml");
}
GetModelName function - this is in a different class.
public string GetModelName(string url)
{
//Import fixture xml
XmlDocument xml = new XmlDocument();
xml.LoadXml(url);
XmlNodeList xnList = xml.SelectNodes("/FixtureModel/");
foreach (XmlNode xn in xnList)
{
ModelName = xn["ModelName"].InnerText;
}
return ModelName;
}
I current get an 'XmlException was unhandled' error in the GetModelName function.
The exact line I am having issues appears to be where I am passing the directory location in.
xml.LoadXml(url);
Does anybody have any ideas on what I am doing wrong.
You should use Load instead of LoadXml: http://msdn.microsoft.com/en-us/library/875kz807.aspx
LoadXml accepts string in XML format instead of Url.
1) LoadXml
is used to parse a string containing an XML document. Load
is used to parse XML retrieved from a URL.
2) You're not properly escaping characters in the URL, as you will find once you use the right method. Either double your backslashes or prefix the string with an @
sign.
精彩评论