Never been to TextSnippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world (or not, you can keep them private!)

« Newer Snippets
Older Snippets »
6 total  XML / RSS feed 

simple Ruby RSS reader

// fetch & parse RSS into an object

require 'rss/2.0'
require 'open-uri'

class RssReader

  def parseFeed (url, length)
    feed_url = url
    output = "";
    open(feed_url) do |http|
      response = http.read
      result = RSS::Parser.parse(response, false)
      output = "\"feedTitle\">#{result.channel.title}
" end return output end end

Example using xmlplarser's saxdriver to parse huge files

// description of your code here

#!/usr/bin/evn ruby
## to run this you call run_amazon_import(datafile) with dataflie = a file to open for parsing, which later is opened based on:
## ("#{RAILS_ROOT}/data/" + datafile + ".xml")
## This is hard coded to look at Item elements, and in this example
## parses out the ASIN as @@product_id and ItemAttributes/Title as @@name
## see check_position_space(name,ch)

require 'xml/saxdriver'
@flag_item  = false

  @@finaldata = []
  @@vars = []
  @@positionSpace = []
  @@currentName = []
def reset_vals
  @@product_id = nil
  @@name = nil
end
def check_position_space(name,ch)
  # with each value within item we check to see if the
  # @@positionSpace (a concatenation of each value's name
  # equals the value we are looking for, if so put it in a global 
  # variable
  if @@positionSpace == 'ASIN'
    @@product_id =  ch
  elsif @@positionSpace == 'ItemAttributesTitle'
        # if I did this again, I would name @@positionSpace
        # with / between names in startElement so it would be simlar to other 
        # ruby xml naming schems so:
        # @@positionSpace == 'ItemAttributesTitle' would be:
        # @@positionSpace == 'ItemAttributes/Title'
        @@name = ch
  end
end

class TestHandler < XML::SAX::HandlerBase
  attr_accessor :data
  def startDocument
    @@data = []
  end
  def startElement(name, attr)
    @flag_item = true if name == 'Item'
    @@positionSpace = '' if name == 'Item'
    if @flag_item == true and name != 'Item'
        @@positionSpace = @@positionSpace + name
    elsif name == 'Item'
      reset_vals
    end
    @@currentName = name
  end
  def endElement(name)
    if @flag_item == true and name != 'Item'
        lenName = name.length
        @@positionSpace = @@positionSpace[0, @@positionSpace.length - lenName]
    end
    if name == 'Item'
      @@finaldata  << @@data.to_s
      @@data = []
          ## Here I would have a fully parsed Item and do something with it
    end
    @flag_item = false if name == 'Item'
  end
  def characters(ch, start, length)
    check_position_space(@@currentName, ch[start, length])
  end
end

def run_amazon_import(datafile)
  @@datafile = datafile
  p = XML::SAX::Helpers::ParserFactory.makeParser("XML::Parser::SAXDriver")
  h = TestHandler.new
  p.setDocumentHandler(h)
  p.setDTDHandler(h)
  p.setEntityResolver(h)
  p.setErrorHandler(h)

  begin
    p.parse("#{RAILS_ROOT}/data/" + datafile + ".xml")
  rescue XML::SAX::SAXParseException
    p(["ParseError", $!.getSystemId, $!.getLineNumber, $!.getMessage])
  end
end

xml to objects

Доступ к дереву XML как к обычным объектам

Для этого можно использовать XSD::Mapping из стандартной библиотеки:

requirexsd/mapping’ 
people = XSD::Mapping.xml2obj(File.read("people.xml")) 
people.person[2].name # => "name3" 


Если в имени тэга присутствует дефис, можно сделать так: people[’foo-bar’]

Ну а выполнить обратное преобразование объектного дерева в XML поможет метод: XSD::Mapping.obj2xml


Somewhat ridiculous XML parser + image generator

Seriously needs caching. SRSLY

<?php
        class ImageGeneration {
                function getInfo($name) {
                        $this->loadDefaultInfo();
                        $XML = new XMLReader;
                        $XML->open("http://chat.hypermutt.net/online/user/".$name.".xml");
                        $wn = array();

                        while($XML->read()) {
                                if ($XML->nodeType == XMLReader::ELEMENT) {
                                        $wn[] = $XML->name;
                                }
                                if ($XML->nodeType == XMLReader::TEXT) {
                                        if ("user/info/nick" == implode('/', $wn)) {
                                                $this->name = $XML->value . ". ";
                                        }
                                        if ("user/info/online" == implode('/', $wn)) {
                                                $this->away = ($XML->value == "TRUE") ? true : false;
                                        }


                                        if ("user/info/connected" == implode('/', $wn)) {
                                                $this->onlinefor = strtotime($XML->value);
                                        }
                                        if ("user/info/timenow" == implode('/', $wn)) {
                                                $sc = (strtotime($XML->value) - $this->onlinefor);
                                                $t = floor($sc/86400);
                                                        $c["days"] = ($t > 0) ? $t."D " : ""; $sc = ($sc-$t*86400);
                                                $t = floor($sc/3600);
                                                        $c["hours"] = ($t > 0) ? $t."H " : ""; $sc = ($sc-$t*3600);
                                                $t = floor($sc/60);
                                                        $c["minutes"] = ($t > 0) ? $t."M " : "";
                                                $this->onlinefor = $c["days"].$c["hours"].$c["minutes"];
                                        }
                                        

                                        if ("user/info/away" == implode('/', $wn)) {
                                                $this->away = ($XML->value == "TRUE") ? true : false;
                                        }
                                        if ("user/info/awaymsg" == implode('/', $wn)) {
                                                $this->awaymessage = $XML->value;
                                        }
                                        if ("user/channels/channel/name" == implode('/', $wn)) {
                                                $this->channels .= str_replace('#','',$XML->value)." ";
                                        }
                                }
                                if ($XML->nodeType == XMLReader::END_ELEMENT) {
                                        array_pop($wn);
                                }
                        }
                        $XML->close();
                }
                
                function loadDefaultInfo() {
                        $this->name = ". ";
                        $this->online = true;
                        $this->onlinefor = "";
                        $this->away = true;
                        $this->awaymessage = "";
                        $this->channels = "";
                }
        
                function drawImage() {
                        header("Content-type: image/png");
                        $image = imagecreatefrompng("background.png");
                                $white = imagecolorallocate($image, 255, 255, 255);
                                $red   = imagecolorallocate($image, 255, 0, 0);
                                $green = imagecolorallocate($image, 0, 255, 0);
                                $feb = "slkscreb.ttf";
                                $fnn = "slkscr.ttf";
                        
                        $sizes["name"]   = imagettfbbox(6, 0, $feb, $this->name);
                        $sizes["online"] = imagettfbbox(6, 0, $feb, "online: ");
                        $sizes["away"]   = imagettfbbox(6, 0, $feb, "away: ");
                        $sizes["yes"]    = imagettfbbox(6, 0, $feb, "yes ");
                        $sizes["#"]     = imagettfbbox(6, 0, $feb, "#: ");
                        
                        imagettftext($image, 6, 0, 22, 8, -$white, $feb, $this->name);
                        imagettftext($image, 6, 0, (22 + $sizes["name"][4]), 8, -$white, $feb, "online:");
                        imagettftext($image, 6, 0, (22 + $sizes["name"][4] + ($sizes["online"][4] - $sizes["away"][4])), 18, -$white, $feb, "away:");
                        imagettftext($image, 6, 0, (22 + $sizes["name"][4] + ($sizes["online"][4] - $sizes["#"][4])),    28, -$white, $feb, "#: ");
                        
                        imagettftext($image, 6, 0, (22 + $sizes["name"][4] + $sizes["online"][4]),  8, -(($this->online) ? $green : $red), $feb, (($this->online) ? "yes" : "no"));
                        imagettftext($image, 6, 0, (22 + $sizes["name"][4] + $sizes["online"][4]), 18, -((!$this->away)  ? $green : $red), $feb, (($this->away)   ? "yes" : "no"));
                        
                        if ($this->online)
                                imagettftext($image, 6, 0, (22 + $sizes["name"][4] + $sizes["online"][4] + $sizes["yes"][4]),  8, $white, $fnn, $this->onlinefor);
                        if ($this->away)
                                imagettftext($image, 6, 0, (22 + $sizes["name"][4] + $sizes["online"][4] + $sizes["yes"][4]), 18, $white, $fnn, $this->awaymessage);
                        imagettftext($image, 6, 0, (22 + $sizes["name"][4] + $sizes["online"][4]), 28, $white, $fnn, $this->channels);
                        
                        imagepng($image);
                        imagedestroy($image);
                }
        }
        
        $x = new ImageGeneration;
        $x->getInfo($_GET['name']);
        $x->drawImage();
?>

Increase the number of simultaneous XmlHttpRequests in Firefox

Firefox doesn't do a lot of simultaneous AJAX (or any kind of HTTP) requests. IE caps it at 2, too. This will allow you to test your XHR overload scripts, or just load pages faster in general.

1. Go to "about:config"
2. Find and edit the following
* network.http.pipelining=false
* network.http.pipelining.maxrequests=4
* network.http.proxy.pipeline=false
3. Make the false's true; I set my maxrequests at 20

XSLT and XHTML DTD's

A quick code snippet to include the right XHTML DTD in your XSL generated output. This took me a bit of reseach to find out:

<xsl:output 
method="xml" 
encoding="utf-8" 
omit-xml-declaration="yes" 
indent="no" 
doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd" 
doctype-public="-//W3C//DTD XHTML 1.0 Strict//EN" />


Another tidbit I found today was:

exclude-result-prefixes="media" 


to exclude unwanted namespace declarations from the output.
« Newer Snippets
Older Snippets »
6 total  XML / RSS feed