Dumb question, but anyway... I am wondering how can one load xml file from url (in Universal Project).
It was quite easy with WPF:
XmlDocument xml = new XmlDocument();
xml.Load(url);
but this isn't working for me here and I really can not find a way around, it's annoying.
Thanks in advance!
You can use HttpClient to do the request. (It's the Microsoft.Net.Http Nuget package.) Once you have a stream from it, there's an overload on XmlDocument.Load which accepts a stream. If you need it parsed as an object, skip XmlDocument.Load and use XmlSerializer instead.
using (HttpClientHandler hHandler = new HttpClientHandler())
{
HttpResponseMessage response = await hClient.GetAsync(URL);
System.IO.Stream oStrm = await response.Content.ReadAsStreamAsync();
XmlSerializer oSer = new XmlSerializer(typeof(T));
return (T)oSer.Deserialize(oStrm);
}
Related
I have a c# solution with an ASMX startup project and having also some other projects. One of these projects (say ThirdProject) has a class (say DataReader) with a method (say ReadData()) which performs a deserialization of a stream. The stream itself is OK, it comes from an embedded resource, and it can be read without error by a StreamReader to a string, and it is really a valid xml string. But the deserialization throws a StackOverflowException.
Now comes the weirdness. For test purposes, I've created an additional project to this c# solution, this is a winform project. If I set this winform project to be the startup project of the solution, then it calls the ThirdProject.DataReader. ReadData() procedure without any error! The deserialization completes!
I've repeated my expreiments by changing the bitness (x86 or x64), and also by changing the target .Net Framework (from 4.0 to 4.7.2), but the result is always the same.
Where should I search the cause of this error? Any hint would be appreciated.
Edit.
The code part in question is this:
using (Stream stream = assembly.GetManifestResourceStream(xmlname))
{
var l = stream.Length;
var ret_obj = ktAntragsdatenAbrufenXmlFormat.Deserialize(stream);
...
}
The stream.Length is 18671. The ktAntragsdatenAbrufenXmlFormat is a static System.Xml.Serialization.XmlSerializer
This code part runs without error:
using (Stream stream = assembly.GetManifestResourceStream(xmlname))
{
var l = stream.Length;
StreamReader reader = new StreamReader(stream);
string text = reader.ReadToEnd();
}
Since reader.ReadToEnd() seems to work fine, try the following:
using (Stream stream = assembly.GetManifestResourceStream(xmlname))
{
var l = stream.Length;
StreamReader reader = new StreamReader(stream);
string text = reader.ReadToEnd();
using (TextReader reader = new StringReader(text))
{
var ret_obj = ktAntragsdatenAbrufenXmlFormat.Deserialize(stream);
}
}
Even if you have a valid xml it can have referrence loops.
If your web service is json, you can set a reference loop handling strategy like ReferenceLoopHandling.Ignore somewhere, havent used that, but there must be an option for that.
If its not json, it just wont go through your webservice as XML, i have no idea if an option even exists in that case. You possibly have to get rid of ref. loops manually before sending and rebuild them once its arrived on the other side.
Nvm, its not your case... ill leave it here anyway
When I create a normal application or class library I can use XDocument.Load(some xml file on the internet) to download and then parse the XML within that file.
However, I'm writing code for a PCL and it seems XDocument does not have the option of a string URI. The only options are System.IO.Stream, System.IO.TextReader, and System.Xml.XmlReader.
How should I proceed to be able to access an XML file on the internet? Should I make use of the new-ish HttpClient and use a stream from that somehow?
I think you need this code:
HttpWebRequest http = (HttpWebRequest)WebRequest.Create("http://your_site.com/etc");
using (WebResponse response = http.GetResponse())
{
Stream stream = response.GetResponseStream();
XDocument xDoc = XDocument.Load(stream);
// Use the xDoc...
}
I am trying to pass through some XML from an external website.
What is the best way of doing this, through c# webpage or asp.MVC?
I tend to use something like this for working with external XML documents / RSS feeds etc:
string sURL = ".....";
// Create a request for the URL.
WebRequest oRequest = WebRequest.Create(sUrl);
// Get the response.
WebResponse oResponse = oRequest.GetResponse();
// Get the stream containing content returned by the server.
Stream oDataStream = oResponse.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader oReader = new StreamReader(oDataStream, System.Text.Encoding.Default);
// Read the content.
string sXML = oReader.ReadToEnd();
// Convert string to XML
XDocument oFeed = XDocument.Parse(sXML);
Either should be fine. MVC is probably easiest (in terms of getting a raw response), but you could do the same in regular ASP.NET just by using a handler (possibly .ashx), or just by clearing the response.
I am building a C# client for a CGI service (not sure what its called exactly).
It accepts a bunch of XML and spits out a response. I have tested it straight in Firefox and it works (see below).
Now I am not sure how to do this in C# code though? Does anyone have a helpful snippet of code, I can't imagine it would be that difficult?
http://www.travelcommunications.co.uk/cgi-bin/d3web_gzip.ssh?%3CTCOML%20version=%22NEWFORMAT%22%3E%3CTransferOnly%3E%3CAvailability%3E%3CRequest%3E%3CAgentCode%3ETEST%3C/AgentCode%3E%3CAgentType%3ETA%3C/AgentType%3E%3CDeparturePointCode%3EALC%3C/DeparturePointCode%3E%3CDeparturePointType%3EAIRPORT%3C/DeparturePointType%3E%3CArrivalPointCode%3EBEN%3C/ArrivalPointCode%3E%3CArrivalPointType%3ERESORT%3C/ArrivalPointType%3E%3CSectorType%3ERETURN%3C/SectorType%3E%3CArrDate%3E10.10.10%3C/ArrDate%3E%3CArrTime%3E10:00%3C/ArrTime%3E%3CRetDate%3E17.10.10%3C/RetDate%3E%3CRetTime%3E10:00%3C/RetTime%3E%3CBrochure%3E001%3C/Brochure%3E%3CAdults%3E2%3C/Adults%3E%3CChildren%3E0%3C/Children%3E%3CInfants%3E0%3C/Infants%3E%3CCurrencyCode%3EUKL%3C/CurrencyCode%3E%3C/Request%3E%3C/Availability%3E%3C/TransferOnly%3E%3C/TCOML%3E
You're looking for the WebClient class.
For example: (2nd EDIT: With GZIP; this code is tested and actually works)
string response;
using (var client = new WebClient()) {
byte[] bytes = client.DownloadData(url);
using(var reader = new StreamReader(new GZipStream(new MemoryStream(bytes), CompressionMode.Decompress)))
response = reader.ReadToEnd();
}
However, if the URL returns raw XML, you can also load the XML directly from the URL, like this:
var doc = XDocument.Load(url);
I am trying to access this webservice, The problem is that sometimes XDocument.Parse is not able to process and generates an error System.Xml.XmlException: Root element is missing. on the line:
XDocument xmlDoc = XDocument.Parse(xmlData);
Even though the XML sent is correct according to my logs.
I was wondering, Is it possible that the StreamReader is not working properly
using (StreamReader reader = new StreamReader(context.Request.InputStream))
{
xmlData = reader.ReadToEnd();
}
XDocument xmlDoc = XDocument.Parse(xmlData);
By the way this is all under a Custom HttpHandler.
Can someone please me guide in the right direction for this.
Thanks
Does it work any more consistently if you use
XDocument.Load(new StreamReader(context.Request.InputStream))
instead of XDocument.Parse?
Your code sample doesn't include logging of the read inputstream. The problem is prior to this point.