在Ruby中格式化一个XML字符串问题,怎么解决

Python040

在Ruby中格式化一个XML字符串问题,怎么解决,第1张

好了 首先是第一步转成16进制: icon = "22 12 41 2 1 8 43 211 42"# =>"22 12 41 2 1 8 43 211 42" icon.split.map {|i| i.to_i.to_s(16) }# =>["16", "c", "29", "2", "1", "8", "2b", "d3", "2a"] 然后是你说的格式化(不太明白你的意思,不知道是不是个位数前面要补0的意思): icon.split.map {|i| i.to_i.to_s(16) }.map { |s| s.size == 1 ? s.insert(0, "0") : s}# =>["16", "0c", "29", "02", "01", "08", "2b", "d3", "2a"] 最后拼起来: icon.split.map {|i| i.to_i.to_s(16) }.map { |s| s.size == 1 ? s.insert(0, "0") : s}.join=>"160c290201082bd32a"

执行SQL语句

require "dbi"

dbh = DBI.connect("DBI:ODBC:#{db_name}",@user,@password)

sth = dbh.execute(%%1)

提取单条记录

# @database is array of references to anonymous hashes

@database = (

{ name =>"Wild Ginger",

city =>"Seattle",

cuisine =>"Asian Thai Chinese Korean Japanese",

expense =>4,

music =>"\0",

meals =>"lunch dinner",

view =>"\0",

smoking =>"\0",

parking =>"validated",

rating=>4,

payment =>"MC VISA AMEX",

},

# { ... }, etc.

)

sub findRestaurants {

my ($database, $query) = @_

return grep {

$query->{city} ?

lc($query->{city}) eq lc($_->{city}) : 1

and $query->{cuisine} ?

$_->{cuisine} =~ /$query->{cuisine}/i : 1

and $query->{min_expense} ?

$_->{expense} >= $query->{min_expense} : 1

and $query->{max_expense} ?

$_->{expense} <= $query->{max_expense} : 1

and $query->{music} ? $_->{music} : 1

and $query->{music_type} ?

$_->{music} =~ /$query->{music_type}/i : 1

and $query->{meals} ?

$_->{meals} =~ /$query->{meals}/i : 1

and $query->{view} ? $_->{view} : 1

and $query->{smoking} ? $_->{smoking} : 1

and $query->{parking} ? $_->{parking} : 1

and $query->{min_rating} ?

$_->{rating} >= $query->{min_rating} : 1

and $query->{max_rating} ?

$_->{rating} <= $query->{max_rating} : 1

and $query->{payment} ?

$_->{payment} =~ /$query->{payment}/i : 1

} @$database

}

要给这段文字添加一个 root 标签,然后对里面的 node 进行遍历。root 标签的名字可以任意定(但是必须添加一个),我这里使用的 root 命名,对于其它的名字也一样。如果你是直接读取的 XML 文件,而不是字符串,可以将文件打开,然后把文件句柄传入 ElementTree.parse() 函数,最后对其返回值进行遍历。

from xml.etree import ElementTree

parsed = ElementTree.XML('''<root>

<composer>Wolfgang Amadeus Mozart</composer> <author>Samuel Beckett</author> <city>London</city>

</root>''')

outstr = []

for node in parsed:

    outstr += ['%s:%s'%(node.tag, node.text)]

print(' '.join(outstr))