Abhijeet  Pandey

Abhijeet Pandey

  • NA
  • 62
  • 1.1k

Error while trying to read xml from URL in asp.net core 2.1

Jul 23 2018 9:06 AM
I am trying to read a XML file from a URL and below is my code in .net core
 
var url = "https://some.com/feeds/newfile.xml";
var httpClient = new HttpClient();
var result = httpClient.GetAsync(url).Result;
var stream = result.Content.ReadAsStreamAsync().Result;
var itemXml = XElement.Load(stream);
 
when the deubgger hits at .load , it throws an error "error on line 22 at column 46: xmlParseEntityRef: no name"
 
Below is the snapshot of the XML where error occurs ie line 22
 
<li>Win management’s support for your LOTO & machine guarding initiatives </li> 

Answers (3)

0
Jeeva Subburaj

Jeeva Subburaj

  • 390
  • 4k
  • 680.4k
Jul 23 2018 9:49 AM
The best approach is to read as string first and replace the & character with space or some other charcter before loading into xelement.
  1. var stringContent= result.Content.ReadAsStringAsync().Result;    
  2. stringContent = stringContent.Replace("&"," ");
Accepted Answer
0
Abhijeet  Pandey

Abhijeet Pandey

  • 0
  • 62
  • 1.1k
Jul 23 2018 9:34 AM
Thank you, for your response.
 
Any way I can encode it before it loads?
0
Jeeva Subburaj

Jeeva Subburaj

  • 390
  • 4k
  • 680.4k
Jul 23 2018 9:23 AM
The ampersand & makes your XML invalid. you have to remove or replace with some other character before you parse the xml content to solve the issue.