readme.xml2

来自「PostgreSQL 8.2中增加了很多企业用户所需要的功能和性能上的提高,其开」· XML2 代码 · 共 266 行

XML2
266
字号
XML-handling functions for PostgreSQL=====================================Development of this module was sponsored by Torchbox Ltd. (www.torchbox.com)It has the same BSD licence as PostgreSQL.This version of the XML functions provides both XPath querying andXSLT functionality. There is also a new table function which allowsthe straightforward return of multiple XML results. Note that the current codedoesn't take any particular care over character sets - this issomething that should be fixed at some point!Installation------------The current build process will only work if the files are incontrib/xml2 in a PostgreSQL 7.3 or later source tree which has beenconfigured and built (If you alter the subdir value in the Makefileyou can place it in a different directory in a PostgreSQL tree).Before you begin, just check the Makefile, and then just 'make' and'make install'.By default, this module requires both libxml2 and libxslt to be installedon your system.  If you do not have libxslt or do not want to use XSLTfunctions, you must edit the Makefile to not build the XSLT functions,as directed in its comments; and edit pgxml.sql.in to remove the XSLTfunction declarations, as directed in its comments.Description of functions------------------------The first set of functions are straightforward XML parsing and XPath queries:xml_is_well_formed(document) RETURNS boolThis parses the document text in its parameter and returns true if thedocument is well-formed XML.  (Note: before PostgreSQL 8.2, this functionwas called xml_valid().  That is the wrong name since validity andwell-formedness have different meanings in XML.  The old name is stillavailable, but is deprecated and will be removed in 8.3.)xpath_string(document,query) RETURNS textxpath_number(document,query) RETURNS float4xpath_bool(document,query) RETURNS boolThese functions evaluate the XPath query on the supplied document, andcast the result to the specified type.xpath_nodeset(document,query,toptag,itemtag) RETURNS textThis evaluates query on document and wraps the result in XML tags. Ifthe result is multivalued, the output will look like:<toptag><itemtag>Value 1 which could be an XML fragment</itemtag><itemtag>Value 2....</itemtag></toptag>If either toptag or itemtag is an empty string, the relevant tag is omitted.There are also wrapper functions for this operation:xpath_nodeset(document,query) RETURNS text omits both tags.xpath_nodeset(document,query,itemtag) RETURNS text omits toptag.xpath_list(document,query,seperator) RETURNS textThis function returns multiple values seperated by the specifiedseperator, e.g. Value 1,Value 2,Value 3 if seperator=','.xpath_list(document,query) RETURNS textThis is a wrapper for the above function that uses ',' as the seperator.xpath_table-----------This is a table function which evaluates a set of XPath queries oneach of a set of documents and returns the results as a table. Theprimary key field from the original document table is returned as thefirst column of the result so that the resultset from xpath_table canbe readily used in joins.The function itself takes 5 arguments, all text.xpath_table(key,document,relation,xpaths,criteria)key - the name of the "key" field - this is just a field to be used asthe first column of the output table i.e. it identifies the record fromwhich each output row came (see note below about multiple values).document - the name of the field containing the XML documentrelation - the name of the table or view containing the documentsxpaths - multiple xpath expressions separated by |criteria - The contents of the where clause. This needs to be specified,so use "true" or "1=1" here if you want to process all the rows in therelation.NB These parameters (except the XPath strings) are just substitutedinto a plain SQL SELECT statement, so you have some flexibility - thestatement isSELECT <key>,<document> FROM <relation> WHERE <criteria>so those parameters can be *anything* valid in those particularlocations. The result from this SELECT needs to return exactly twocolumns (which it will unless you try to list multiple fields for keyor document). Beware that this simplistic approach requires that youvalidate any user-supplied values to avoid SQL injection attacks.Using the functionThe function has to be used in a FROM expression. This gives the followingform:SELECT * FROMxpath_table('article_id', 	'article_xml',	'articles', 	'/article/author|/article/pages|/article/title',	'date_entered > ''2003-01-01'' ') AS t(article_id integer, author text, page_count integer, title text);The AS clause defines the names and types of the columns in thevirtual table. If there are more XPath queries than result columns,the extra queries will be ignored. If there are more result columnsthan XPath queries, the extra columns will be NULL.Note that I've said in this example that pages is an integer.  Thefunction deals internally with string representations, so when you sayyou want an integer in the output, it will take the stringrepresentation of the XPath result and use PostgreSQL input functionsto transform it into an integer (or whatever type the AS clauserequests). An error will result if it can't do this - for example ifthe result is empty - so you may wish to just stick to 'text' as thecolumn type if you think your data has any problems.The select statement doesn't need to use * alone - it can reference thecolumns by name or join them to other tables. The function produces avirtual table with which you can perform any operation you wish (e.g.aggregation, joining, sorting etc). So we could also have:SELECT t.title, p.fullname, p.email FROM xpath_table('article_id','article_xml','articles',            '/article/title|/article/author/@id',            'xpath_string(article_xml,''/article/@date'') > ''2003-03-20'' ')            AS t(article_id integer, title text, author_id integer),      tblPeopleInfo AS p WHERE t.author_id = p.person_id;as a more complicated example. Of course, you could wrap allof this in a view for convenience.Multivalued resultsThe xpath_table function assumes that the results of each XPath querymight be multi-valued, so the number of rows returned by the functionmay not be the same as the number of input documents. The first rowreturned contains the first result from each query, the second row thesecond result from each query. If one of the queries has fewer valuesthan the others, NULLs will be returned instead.In some cases, a user will know that a given XPath query will returnonly a single result (perhaps a unique document identifier) - if usedalongside an XPath query returning multiple results, the single-valuedresult will appear only on the first row of the result. The solutionto this is to use the key field as part of a join against a simplerXPath query. As an example:CREATE TABLE test(  id int4 NOT NULL,  xml text,  CONSTRAINT pk PRIMARY KEY (id)) WITHOUT OIDS;INSERT INTO test VALUES (1, '<doc num="C1"><line num="L1"><a>1</a><b>2</b><c>3</c></line><line num="L2"><a>11</a><b>22</b><c>33</c></line></doc>');INSERT INTO test VALUES (2, '<doc num="C2"><line num="L1"><a>111</a><b>222</b><c>333</c></line><line num="L2"><a>111</a><b>222</b><c>333</c></line></doc>');The query:SELECT * FROM  xpath_table('id','xml','test', '/doc/@num|/doc/line/@num|/doc/line/a|/doc/line/b|/doc/line/c','1=1') AS t(id int4, doc_num varchar(10), line_num varchar(10), val1 int4, val2 int4, val3 int4)WHERE id = 1 ORDER BY doc_num, line_numGives the result: id | doc_num | line_num | val1 | val2 | val3----+---------+----------+------+------+------  1 | C1      | L1       |    1 |    2 |    3  1 |         | L2       |   11 |   22 |   33To get doc_num on every line, the solution is to use two invocationsof xpath_table and join the results:SELECT t.*,i.doc_num FROM   xpath_table('id','xml','test',   '/doc/line/@num|/doc/line/a|/doc/line/b|/doc/line/c','1=1')         AS t(id int4, line_num varchar(10), val1 int4, val2 int4, val3 int4),  xpath_table('id','xml','test','/doc/@num','1=1')         AS i(id int4, doc_num varchar(10))WHERE i.id=t.id AND i.id=1ORDER BY doc_num, line_num;which gives the desired result: id | line_num | val1 | val2 | val3 | doc_num----+----------+------+------+------+---------  1 | L1       |    1 |    2 |    3 | C1  1 | L2       |   11 |   22 |   33 | C1(2 rows)XSLT functions--------------The following functions are available if libxslt is installed (this isnot currently detected automatically, so you will have to amend theMakefile)xslt_process(document,stylesheet,paramlist) RETURNS textThis function appplies the XSL stylesheet to the document and returnsthe transformed result. The paramlist is a list of parameterassignments to be used in the transformation, specified in the form'a=1,b=2'. Note that this is also proof-of-concept code and theparameter parsing is very simple-minded (e.g. parameter values cannotcontain commas!)Also note that if either the document or stylesheet values do notbegin with a < then they will be treated as URLs and libxslt willfetch them. It thus follows that you can use xslt_process as a meansto fetch the contents of URLs - you should be aware of the securityimplications of this.There is also a two-parameter version of xslt_process which does notpass any parameters to the transformation.Feedback--------If you have any comments or suggestions, please do contact me atjgray@azuli.co.uk. Unfortunately, this isn't my main job, so I can'tguarantee a rapid response to your query!

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?