Parsing a XML response back to JSON - c#

I'm working on project where i have to make an API request. When I post a JSON request to the server I get the following XML as response:
"<response>
\r\n
<data>
\r\n
<status no=\"0\" substatus=\"0\">
Connection succeeded
</status>\r\n
</data>
\r\n
</response>"
I need to convert the response back to JSON. But when I try to parse it i'm getting an error saying
'Unexpected character encountered while parsing value: <. Path '',
line 0, position 0.'
I'm using NewtonSoftJSON for conversion.
This is the code I'm using to convert the XML string back to JSON:
var response = JsonConvert.DeserializeXmlNode(xmlResponse);
How can I achieve this?

I would be highly confused by any webapi that expect JSON as input and return XML as its response. But if that is really what you're looking at then you need to take the approach in Serializing that XML response into either an XmlDocument or the newer XDocument/XNode and then Serialize an instance of one of those into JSON.
The XmlDocument type has a Load method that consumes a XmlReader. (it also offers a LoadXml but I wanted to show several options here).
The XDocument type has a Parse method that consumes a string with XML.
Based on your example input you can use two approaches:
var xml = #"<response>
<data>
<status no=""0"" substatus=""0"">
Connection succeeded
</status>
</data>
</response>";
// xmldocument
var xmlReader = XmlReader.Create(new StringReader(xml));
var doc = new XmlDocument();
doc.Load(xmlReader);
var response = JsonConvert.SerializeXmlNode(doc);
response.Dump("XMLDoc to Json "); // LINQPad output
// or XDOcument
response = JsonConvert.SerializeXNode(XDocument.Parse(xml));
response.Dump("XDocument to Json");// LINQPad output
And this will be the result:

There is no direct conversion from XML to JSON. And you should be using a XML parser for this response.
Parsing XML (C#) :
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/parsing-xml
I also suggest reading a little bit more about serialization, since this question actually makes no sense.

I have figured out the issue. rene's answer helped to figure out the how to convert from xml to json. But the issue was with my response. I was able to fix it by removing the /" and unwanted double quotes from the response.
response = response.Replace("<response>\"", "<response>")
.Replace("\"<response>", "<response>")
.Replace("\\", "")
.Replace("rn", string.Empty);
var xmlReader = XmlReader.Create(new StringReader(response));
var doc = new XmlDocument();
doc.Load(xmlReader);
var jsonResponse = JsonConvert.SerializeXmlNode(doc);

Related

C# Error in readering XML from URL

I have an XML reader but I receive an error when I'm trying to read the XML from an URL (external source).
This is the code I have ATM:
XmlReader xmlReader = XmlReader.Create("http://dl.bukkit.org/api/1.0/downloads/projects/craftbukkit/view/build-1330/");
while (xmlReader.Read())
{
}
Very simple code, but it returns an error which says:
Data at the root level is invalid. Line 1, position 1.
Any idea?
I can't edit the XML, because it's not mine.
Thanks in advance!
If you use Fiddler to analyze the response returned by the sever, you'll see, that you get JSON instead of XML. You can add a parameter to the URL to get XML:
http://dl.bukkit.org/api/1.0/downloads/projects/craftbukkit/view/build-1330/?format=xml

Parsing web pages via C#, XmlDocument.LoadXml

I'm trying to download a web page and parse it. I need to reach every node of html document. So I used WebClient to download, which works perfectly. Then I use following code segment to parse the document:
WebClient client = new WebClient();
Stream data = client.OpenRead("http://web.cs.hacettepe.edu.tr/~bil339/");
StreamReader reader = new StreamReader(data);
string xml = reader.ReadToEnd();
data.Close();
reader.Close();
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.loadXml(xml);
In last line, program waits for some time, then crashes. It says there are errors in HTML code, this wasn't expected, that shouldn't be here, etc.
Any suggestions to fix this? Other techniques to parse HTML code are welcome (In C#, of course.)
Use the HTMLAgilityPack to parse HTML. Well-formed HTML is not XML and can't be parsed as such. For instance, it lacks the <?xml version="1.0" encoding="UTF-8"?> preamble that all XML files require. The HTML Agility Pack is more forgiving.

XML Illegal Characters in path

I am querying a soap based service and wish to analyze the XML returned however when I try to load the XML into an XDoc in order to query the data. am getting an 'illegal characters in path' error message? This (below) is the XML returned from the service. I simply want to get the list of competitions and put them into a List I have setup. The XML does load into an XML Document though so must be correctly formatted?.
Any advice on the best way to do this and get round the error would be greatly appreciated.
<?xml version="1.0" ?>
- <gsmrs version="2.0" sport="soccer" lang="en" last_generated="2010-08-27 20:40:05">
- <method method_id="3" name="get_competitions">
<parameter name="area_id" value="1" />
<parameter name="authorized" value="yes" />
<parameter name="lang" value="en" />
</method>
<competition competition_id="11" name="2. Bundesliga" soccertype="default" teamtype="default" display_order="20" type="club" area_id="80" last_updated="2010-08-27 19:53:14" area_name="Germany" countrycode="DEU" />
</gsmrs>
Here is my code, I need to be able to query the data in an XDoc:
string theXml = myGSM.get_competitions("", "", 1, "en", "yes");
XmlDocument myDoc = new XmlDocument();
MyDoc.LoadXml(theXml);
XDocument xDoc = XDocument.Load(myDoc.InnerXml);
You don't show your source code, however I guess what you are doing is this:
string xml = ... retrieve ...;
XmlDocument doc = new XmlDocument();
doc.Load(xml); // error thrown here
The Load method expects a file name not an XML itself. To load an actual XML, just use the LoadXml method:
... same code ...
doc.LoadXml(xml);
Similarly, using XDocument the Load(string) method expects a filename, not an actual XML. However, there's no LoadXml method, so the correct way of loading the XML from a string is like this:
string xml = ... retrieve ...;
XDocument doc;
using (StringReader s = new StringReader(xml))
{
doc = XDocument.Load(s);
}
As a matter of fact when developing anything, it's a very good idea to pay attention to the semantics (meaning) of parameters not just their types. When the type of a parameter is a string it doesn't mean one can feed in just anything that is a string.
Also in respect to your updated question, it makes no sense to use XmlDocument and XDocument at the same time. Choose one or the another.
Following up on Ondrej Tucny's answer :
If you would like to use an xml string instead, you can use an XElement, and call the "parse" method. (Since for your needs, XElement and XDocument would meet your needs)
For example ;
string theXML = '... get something xml-ish...';
XElement xEle = XElement.Parse(theXML);
// do something with your XElement
The XElement's Parse method lets you pass in an XML string, while the Load method needs a file name.
Why not
XDocument.Parse(theXml);
I assume this will be the right solution
If this is really your output it is illegal XML because of the minus characters ('-'). I suspect that you have cut and pasted this from a browser such as IE. You must show the exact XML from a text editor, not a browser.

Need to parse a xml string

I need to a parse an xml string(.NET, C#) which , unfortunately, is not well formed.. the xml stream that i am getting back is
<fOpen>true</fOpen>
<ixBugParent>0</ixBugParent>
<sLatestTextSummary></sLatestTextSummary>
<sProject>Vantive</sProject>
<ixArea>9</ixArea>
I have tried using a xml reader, but its crashing out because it thinks ,and rightfully so, there are 2 node elements wheneever it tries to parse
Is there something that I can do with this ? I cant change the XML, cause I have no control of the code that sends the XML back ..
Any help, would be appreciated.
Thanks and Regards
Gagan Janjua
I think you can use the XmlParserContext in one of the XmlTextReader overloads to specify that the node type is an XmlNodeType.Element, similar to this example from MSDN (http://msdn.microsoft.com/en-us/library/cakk7ha0.aspx):
XmlTextReader tr = new XmlTextReader("<element1> abc </element1>
<element2> qrt </element2>
<?pi asldfjsd ?>
<!-- comment -->", XmlNodeType.Element, null);
while(tr.Read()) {
Console.WriteLine("NodeType: {0} NodeName: {1}", tr.NodeType, tr.Name);
}
What you are getting back is a well-formed XML fragment but as you pointed out, not a well-formed XML document. Can you
wrap a top-level element around the returned elements? or
reference the returned XML fragment as an external entity from within a shell XML document, and pass the shell document to the XML reader?

How to return XML to the Response stream?

I'm trying to return an xml string from a IHttpHandler to a like this:
context.Response.Write(xml);
When I receive the response in my .aspx.cs I try to load the document as follows:
var xml = XDocument.Load(xmlString);
but I get an Illegal Characters in Path error message.
I've also tried
context.Response.Write(context.Server.HtmlEncode(xml));
and
var xml = XDocument.Load(Server.HtmlDecode(xmlString));
but I get the same message. Is there any way I can return XML from my IHttpHandler?
replace this:
var xml = XDocument.Load(xmlString);
with this:
var xml = XDocument.Parse(xmlString);
XDocument.Load(String) takes a file path. You want to use one of the overloads that accepts a Reader object.
Try setting the context.Response.ContentType = "application/xml"
Obviously also make sure the XML is well formed, MSDN has an example of returning XML from a HTTP Handler.
Try putting the XML into a validator (or open in a browser) to highlight any issues.

Categories