The xpathdocument object provides a very convenient way to load XML resources, as long as the accessed resource path is correct and the current process has the permission to access, you can directly load the XML file through the object's constructor, and then operate the XML file in an object-oriented manner. If the XML file to be accessed denies the current process from being accessed anonymously, you can set the access level of the XML file or grantProgramSolve this problem with a higher security level. However, if the XML file to be accessed is an external resource and we do not have the permission to modify the access security level, the following two methods can be used to try.
Method 1: Try to use the physical path of the resource for access
The followingCodeUse the server. mappath method to convert the resource URL to the physical path on the server, and then use the xpathdocument object constructor to load the resource.
1 String URL = " Http://www.example.com/resource/demo.xml " ;
2 String Sabsolutepath = Httpcontext. Current. server. mappath (server. urldecode (URL ));
3 Xpathdocument oxpathdocument = New Xpathdocument (sabsolutepath );
Note that the URL may contain escaped characters. Therefore, you must use the server. urldecode method to perform the decode operation.
Method 2: Try to access resources as a specific user
The following code demonstrates accessing XML resources as the current system user.
1 String URL = " Http://www.example.com/resource/demo.xml " ;
2
3 Httpwebrequest request = (Httpwebrequest) webrequest. Create ( New Uri (URL ));
4 Request. Credentials = Credentialcache. defaultnetworkcredentials;
5
6 Httpwebresponse response = (Httpwebresponse) request. getresponse ();
7 Streamreader SR = New Streamreader (response. getresponsestream (), encoding. utf8 );
8 Xpathdocument oxpathdocument = New Xpathdocument (SR );
Of course, you can also access it with a specific user, such:
Request. Credentials = New Networkcredential ( " Username " , " Password " , " Domain " );
This allows the current program to access XML external resources.