Thursday, September 6, 2007

I Am "using System.Xml.Linq;"

As you know, I've come to believe that REST is the correct default way for me to program web services. (Whether it's the correct way for you to do so is an entirely separate question.) Part of my experimentation in this space has been to embrace the idea that "XHTML is the new XML". That is, that data should be encoded using standard XHTML tags rather than custom XML grammars wherever possible.

 

The idea has enormous potential due not least to the fact that it makes your browser a debugging environment for your web services. However, browsers aren't the real target: custom web service clients are. And in the .NET space, there hasn't been a great API for consuming XHTML as an object graph. Oh, you could use XPath, but that's a bit messy. XmlSerializer would be preferable, but unfortunately it's no good at deserializing based on things like the value of a class attribute of a tag.

 

Now, however, we have Linq. So given a document like this:

<html xmlns="xhtml namespace">
<body>
<ul class="alternates">
<li>3</li>
<li>4</li>
<li>5</li>

</ul>
</body>
</html>

we can do things like this:

 

XNamespace xhtmlns = "http://www.w3.org/1999/xhtml"; 

var alternates = from ul in document.Element(xhtmlns + "html").Element(xhtmlns + "body").Element(xhtmlns + "ul")
where ul.Attribute("class").Value == "alternates"
select from li in ul.Elements("li") select li.Value;
 

which is extremely damn cool. Of course, I can do something even more useful and initialize objects with the results of my query doing something like this instead:

var alternates = from ul
in document.Element(xhtmlns + "html").Element(xhtmlns + "body").Elements(xhtmlns + "ul")
where ul.Attribute("class").Value == "alternates"
select
from li
in ul.Elements("li")
select new Alternate { Value = li.Value } ;


where Alternate is a class I've defined with a public property called Value. I imagine you can get it to work with an anonymous type, too, but so far that hasn't worked for me. Anyway, it's wicked cool nonetheless.

2 comments:

  1. Try this:



    var strings =

    from ul in doc.Element(xhtml.html).Element(xhtml.body).Elements(xhtml.ul)

    where ul.Attribute(xhtml.@class).Value == "alternates"

    from li in ul.Elements(xhtml.li)

    select li.Value;

    ReplyDelete
  2. I want to execute stored procedure in asp.net and that executed stored procedured data want into xml file.



    It is possible then reply me on purvesh143in@yahoo.co.in these is my id.

    ReplyDelete