Monday, July 12, 2010

Outputting XML in aspx file...

This one, although seemingly difficult for those of you who are unfamiliar with asp.net, is surprisingly complex (sense the sarcasm please)...

you ready?

here we go...
Step 1) in your page directive, add the following: ContentType="text/xml"

This tells the browser that the output will be in XML format

Step 2) Pour yourself a beer, and enjoy the XML that will result from now on.

BAM... you're done, and welcome...

Friday, July 2, 2010

Linq to XML - Creating XDocument with Dynamic Values

I had the need to create a service utility function that would take in an object (a predefined customer object), and output the object as XML...

I decided to use Linq to XML, mainly because it's AMAZING, and will do everything for you... Linq to SQL has its fair share of issues (even Microsoft will admit this), but the Linq to ___ suite outside of to SQL is amazing, ESPECIALLY Linq to XML... anyway, let me stop stroking bill gates' ego, and get to the issue at hand...

so, I needed to create a function "customerToXML" that would take in an object (in this case a Customer Object), and would spit out XML. I decided that the output should be in the form of an XDocument...

The issue was that in defining the XDocument, Linq to XML allows you to define the XML right there in the code!!!

I needed to however not just define the XML, but also fill it with dynamic data that would be populated depending on the Customer object passed to the funtion...

The answer I was looking for was in Microsoft's MSDN Library.

Here's what I had to do (don't ask why i'm using VB.Net... sometimes clients don't know what they're asking for, but they're still always right... right?)


Public Function objectToXML(ByVal customer as Customer) as XDocument
Dim customerAsXML as XDocument = _
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<customer id=<%= customer.customer_id %> >
<customer_name><%= customer.customer_name %></customer_name>
<customer_acct><%= customer.customer_acct %></customer_acct>
</customer>
Return customerAsXML
End Function


As you can see, all you have to do is put the delimiter to embed expressions...

I found this answer here


Anyway, I hope this helps