Supplying Authentication Credentials to XmlResolver when Reading from a File
When resolving a URL to a file that contains the XML data to read, the file may have a restricted access policy. If authentication is required to access a network resource, use the Credentials property to specify the necessary credentials. If the Credentials property is not set, then credentials are set to null.
For example, assume that credentials are needed when requesting data from the Web for authentication purposes. If the Web virtual directory allows anonymous access, then the property does not need to be set for anonymous access. However, if the directory does not allow anonymous access, then you need to supply credentials. The following example creates an XmlReader that uses an XmlUrlResolver with default credentials to access the http://localhost/bookstore/inventory.xml site.
' Create a resolver with default credentials. Dim resolver as XmlUrlResolver = new XmlUrlResolver() resolver.Credentials = System.Net.CredentialCache.DefaultCredentials ' Set the reader settings object to use the resolver. settings.XmlResolver = resolver ' Create the XmlReader object. Dim reader as XmlReader = XmlReader.Create("http://ServerName/data/books.xml", settings)
Different credentials can be supplied for different URIs and added to a credential cache. These credentials are used to check authentication for the different URIs regardless of the original source of the XML. The following example shows adding credentials to a cache.
' Create the credentials. Dim myCred As NetworkCredential = New NetworkCredential(UserName,SecurelyStoredPassword,Domain) Dim myCache As CredentialCache = New CredentialCache() myCache.Add(new Uri("http://www.contoso.com/"), "Basic", myCred) myCache.Add(new Uri("http://app.contoso.com/"), "Basic", myCred) ' Set the credentials on the XmlUrlResolver object. Dim resolver As XmlUrlResolver = New XmlUrlResolver() resolver.Credentials = myCache ' Compile the style sheet. Dim xslt As XslCompiledTransform = New XslCompiledTransform() xslt.Load("http://serverName/data/xsl/order.xsl", XsltSettings.Default, resolver)