0

I have a script that perfectly generates objects from local xml file, now I want to port it in WebGL, but when I am trying to upload xml from server local host doesn't response. The script that I use for reading xml file from URL:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream receiveStream = response.GetResponseStream();
XDocument xdoc = XDocument.Load(receiveStream);
receiveStream.Close();

Is there any way to load xml file in Unity for reading data and dynamic objects generation?

Programmer
  • 121,791
  • 22
  • 236
  • 328
shss
  • 3
  • 2

1 Answers1

0

HttpWebRequest is from the System.Net namespace and you can't use any API from the System.Net namespace with WebGL platform. You have to use the WWW or UnityWebRequest API to download the data instead of HttpWebRequest. Once you download the data with HttpWebRequest, use XDocument.Parse to convert the received data into XDocument object.

void Start()
{
    StartCoroutine(getRequest("http:///www.yoururl.com"));
}

IEnumerator getRequest(string uri)
{
    //Make request
    UnityWebRequest uwr = UnityWebRequest.Get(uri);
    yield return uwr.SendWebRequest();

    if (uwr.isHttpError)
    {
        Debug.Log("Error While Sending: " + uwr.error);
    }
    else
    {
        Debug.Log("Received: " + uwr.downloadHandler.text);

        //Convert to xml
        XDocument xdoc = XDocument.Parse(uwr.downloadHandler.text);
    }
}

This is for Get request. If post request, see this post.

Programmer
  • 121,791
  • 22
  • 236
  • 328
  • Thanks, it very helped me! It reads xml very well but i can't load it to XDocument, because of error: "Text node cannot appear in this state. Line 1, position 1" – shss May 13 '18 at 09:15
  • Sorry there is a typo in my answer. That should be `XDocument.Parse` as I mention. I said this in the beginning of my answer but messed up in the code. Also, that should be inside the else statement to make sure you don't load xml when there is a download error. See the updated answer. – Programmer May 13 '18 at 13:35
  • Yeah, for sure I've used "Parse" instead "Load", seems it was my XML problem, because of BOM. – shss May 14 '18 at 03:12
  • Ok. Got it fixed now? – Programmer May 14 '18 at 04:50
  • 1
    Yep, works like a charm with loading options: `XDocument xdoc = XDocument.Parse(uwr.downloadHandler.text, LoadOptions.PreserveWhitespace);` – shss May 14 '18 at 05:37