Wednesday, March 21, 2012

XML Parsing

I am fetching data from my server through AJAX, and some of the contained data is XML formatted. I am happy to instansiate XML Document objects if required, but it seems that at least some XML handling is included within the Framework. Is there any way to access the inbuilt XML processing client-side, or will I have to declare relevant objects or libraries and process them as I would in a standard HTML page?

Thanks in advance,

James

If you create a .NET class that represents the XML instead of passing back xml,( you pass back the object), you can return that class type in your web service method and the runtime will generate a javascript version of it off your [scriptmethod] for you.

so if I made a class in C# like

public class TesterClass {private int myVar;public int MyProperty {get {return myVar; }set { myVar =value; } }private int myVar2;public int MyProperty2 {get {return myVar2; }set { myVar2 =value; } } }

then if you hit your webservice.asmx/js you can see that it creates a javascript class version of it for you.

function MyTest(){MyProperty:0;MyProperty2:0;}

Now you can work with objects instead of XML.. slick eh?


I assume you're using Sys.Net.WebRequest to request the XML formatted data. In your call back function, you can retrieve the XML data by using the xml property of the WebRequestExecutor class. This only works, however, if the data's content type if text/xml. If it's a mix of plain text and XML, you'll have extract the XML data and load it into an XML DOM.


Just a sample call back function:

function request_callBack(executor, eventArgs){if (executor.get_responseAvailable()) { var xmlDom = executor.get_xml(); alert(xmlDom.documentElement.nodeName); }}


Thanks for the answers, but I've already got structured objects being passed back from a webservice. One of the fields that is passed back within the object contains XML. I can happily plug-in a cross-browser javascript XML library, but this is a bit superfluous if the XML handling is already being provided with my structured objects and their scripts. If anyone is able to confirm or deny the requirement to pass this XML field to the same objects that I'd use for HTML handling within an html file I'd be really grateful.

Thanks,

James


If you can convert your xml in that field into a JSON string, then you could use the method listed in the link below:

http://ajax.asp.net/docs/ClientReference/Sys.Serialization/JavascriptSerializerClass/JavascriptSerializerDeserializeMeth.aspx

No comments:

Post a Comment