Home Explore Blog CI



postgresql

5th chunk of `doc/src/sgml/xml2.sgml`
54b353a0f18ac6c2aee09afce1cd052dddfd2328b5ccdda60000000100000906

<programlisting>
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;
</programlisting>
   as a more complicated example. Of course, you could wrap all
   of this in a view for convenience.
  </para>

  <sect3 id="xml2-xpath-table-multivalued-results">
   <title>Multivalued Results</title>

   <para>
    The <function>xpath_table</function> function assumes that the results of each XPath query
    might be multivalued, so the number of rows returned by the function
    may not be the same as the number of input documents. The first row
    returned contains the first result from each query, the second row the
    second result from each query. If one of the queries has fewer values
    than the others, null values will be returned instead.
   </para>

   <para>
    In some cases, a user will know that a given XPath query will return
    only a single result (perhaps a unique document identifier) &mdash; if used
    alongside an XPath query returning multiple results, the single-valued
    result will appear only on the first row of the result. The solution
    to this is to use the key field as part of a join against a simpler
    XPath query. As an example:

<programlisting>
CREATE TABLE test (
    id int PRIMARY KEY,
    xml text
);

INSERT INTO test VALUES (1, '&lt;doc num="C1"&gt;
&lt;line num="L1"&gt;&lt;a&gt;1&lt;/a&gt;&lt;b&gt;2&lt;/b&gt;&lt;c&gt;3&lt;/c&gt;&lt;/line&gt;
&lt;line num="L2"&gt;&lt;a&gt;11&lt;/a&gt;&lt;b&gt;22&lt;/b&gt;&lt;c&gt;33&lt;/c&gt;&lt;/line&gt;
&lt;/doc&gt;');

INSERT INTO test VALUES (2, '&lt;doc num="C2"&gt;
&lt;line num="L1"&gt;&lt;a&gt;111&lt;/a&gt;&lt;b&gt;222&lt;/b&gt;&lt;c&gt;333&lt;/c&gt;&lt;/line&gt;
&lt;line num="L2"&gt;&lt;a&gt;111&lt;/a&gt;&lt;b&gt;222&lt;/b&gt;&lt;c&gt;333&lt;/c&gt;&lt;/line&gt;
&lt;/doc&gt;');

SELECT * FROM
  xpath_table('id','xml','test',
              '/doc/@num|/doc/line/@num|/doc/line/a|/doc/line/b|/doc/line/c',
              'true')
  AS t(id int, doc_num varchar(10), line_num varchar(10), val1 int, val2 int,

Title: Handling Multivalued Results with xpath_table
Summary
The xpath_table function can return multiple rows for each input document if the XPath queries have multiple results, with null values returned if one query has fewer values than the others, and techniques such as using the key field in a join or creating a simpler XPath query can help handle single-valued results alongside multivalued results.