Introduction
Sometimes, in software projects we need to make the access to data more quickly and efficiently. So, there is the usefulness of the XPathNavigator
object, which allows us to access the XML data more efficiently, quickly and in an easier way. Take a look.
Background
- ASP.NET C# initial/medium knowledge
- XML, XPATH knowledge
Using the Code
Given below is the source code, you can use it and even improve it. I hope that helps you in the future.
We'll try to parse the next XML document:
="1.0"="UTF-8"
<Configurations>
<AccessConfigurations>
<Username><![CDATA[</Username>
<Password><![CDATA[</Password>
</AccessConfigurations>
</Configurations>
[Serializable]
public class MyCredential
{
#region Properties.
private string _username;
public string Username
{
get { return _username; }
set { _username = value; }
}
private string _password;
public string Password
{
get { return _password; }
set { _password = value; }
}
#endregion
#region Constructors.
public MyCredential()
{
}
public MyCredential(string username, string password)
{
this.Username = username;
this.Password = password;
}
#endregion
}
public MyCredential[] GetAccessConfigurations()
{
HttpServerUtility server = HttpContext.Current.Server;
string username = string.Empty;
string password = string.Empty;
List<MyCredential> credentials = new List<MyCredential>();
try
{
string fileUrl = @".\TestFiles\Test.xml";
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load(server.MapPath(fileUrl));
XPathNavigator nav = xmlDocument.CreateNavigator();
username = nav.SelectSingleNode("Configurations/AccessConfigurations/Username").Value;
password = nav.SelectSingleNode("Configurations/AccessConfigurations/Password").Value;
credentials.Add(new MyCredential(username, password));
return credentials.ToArray();
}catch (Exception innerException)
{
throw innerException;
}
}
Points of Interest
I hope you learned with this tutorial. If you have any questions, please send them to davidalexrosa@gmail.com. Thanks!
History
- 12th October, 2008: Initial post
In the next article, we will use conditions and CDATA
Sections with XPathNavigator
. I hope you enjoy it as much as I do.
Degree in Computer Engineering at the Autonomous University of Lisbon - Portugal (UAL - Universidade Autónoma de Lisboa).
Worked at Unisys Portugal in ASP.NET 2.0 Technology and Microsoft Office SharePoint Server 2007 not forgetting adjacent technologies.
Worked also as Technical Coordinator of the GMTS's (Global Media Technology Solutions) Junior Development Team in the Portals Area, using Microsoft Office SharePoint Server 2007, ASP.NET, WPF, Silverlight and Frameworks 2.0, 3.0 and 3.5.
Now,he is working for GISP Software SA, a software house focused in the media market, as Software Engineer.