Home > Projects > X Path Translator
This class translates simple XPath expressions into SQL queries. A very simple translation of relational tables to XML documents is assumed so that simple queries can be performed using XPath statements.
The translation works as follows:
| Table A | |||
|---|---|---|---|
| A1 | A2 | A3 | A4 |
| 1 | 2 | 3 | 4 |
| 11 | 22 | 33 | 44 |
| 111 | 222 | 333 | 444 |
| Table B | ||
|---|---|---|
| B1 | B2 | B3 |
| 1 | 2 | 3 |
| 11 | 22 | 33 |
| 111 | 222 | 333 |
Would correspond to:
<Data>
<A>
<A1>1</A1>
<A2>2</A2>
<A3>3</A3>
<A4>4</A4>
</A>
<A>
<A1>11</A1>
<A2>22</A2>
<A3>33</A3>
<A4>44</A4>
</A>
<A>
<A1>111</A1>
<A2>222</A2>
<A3>333</A3>
<A4>444</A4>
</A>
<B>
<B1>1</B1>
<B2>2</B2>
<B3>3</B3>
</B>
<B>
<B1>11</B1>
<B2>22</B2>
<B3>33</B3>
</B>
<B>
<B1>111</B1>
<B2>222</B2>
<B3>333</B3>
</B>
</Data>
So XPath statements can be written to get data from the database considering this structure. For example:
| SQL | XPath Expression |
|---|---|
| select * from A | //A or /Data/A |
| select A1 from A | //A/A1 or /Data/A/A1 |
| select * from B where B2=22 | //B[B2=22] |
| select * from B where B2=22 and B3!=333 | //B[B2=22 and B3!=333] |
This translator only supports simple XPath statements. The primary limitations are:
- No way to perform joins.
- XPath * operator not supported.
- Must use absolute paths.
- Axes and functions (except starts-with and contains) not supported.
- // is treated as shorthand for /Data/ and so text after will be table name and will not match columns.
- Conditions in [] are limited to expressions that are valid in both XPath and SQL where clause.
- Attributes are not supported (but are not really needed).
Example of Use
public class Translate
{
public static void main(String[] args)
{
XPathTranslator translator=new XPathTranslator();
for(String xpath : args)
System.out.println(translator.translate(xpath));
}
}