I have a problem an at the moment no idea to solve it ;-(
I have a category structure as input document (xml) and want to build a path structure.
I can only use xslt and want to generate a new xml structure.
The input structure looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<Positions>
<Positionen>
<ID>1</ID>
<Parent></Parent>
</Positionen>
<Positionen>
<ID>2</ID>
<Parent>1</Parent>
</Positionen>
<Positionen>
<ID>3</ID>
<Parent>1</Parent>
</Positionen>
<Positionen>
<ID>4</ID>
<Parent>2</Parent>
</Positionen>
<Positionen>
<ID>5</ID>
<Parent>4</Parent>
</Positionen>
<Positionen>
<ID>6</ID>
<Parent>2</Parent>
</Positionen>
</Positions>
The output structure should be this:
<?xml version="1.0" encoding="UTF-8"?>
<Positions>
<Positionen>
<ID>1</ID>
<Parent></Parent>
<Path>1</Path>
</Positionen>
<Positionen>
<ID>2</ID>
<Parent>1</Parent>
<Path>1/2</Path>
</Positionen>
<Positionen>
<ID>3</ID>
<Parent>1</Parent>
<Path>1/3</Path>
</Positionen>
<Positionen>
<ID>4</ID>
<Parent>2</Parent>
<Path>1/2/4</Path>
</Positionen>
<Positionen>
<ID>5</ID>
<Parent>4</Parent>
<Path>1/2/4/5</Path>
</Positionen>
<Positionen>
<ID>6</ID>
<Parent>2</Parent>
<Path>1/2/6</Path>
</Positionen>
</Positions>
How can I do this with xslt with a recursion?
Hoping fore some help. Thanks in advance.
LStrike
Some answers to this question are good but rather inefficient (O(N^2)).
This is so, because the path is constructed from scratch for every
Positionenelement. The average path length is N/2 and there are NPositionenelements. That means that N*N/2 operations are needed as minimum to construct all paths — and this is quadratical time complexity.Here is a more efficient O(N*log(N)) — could be even (O(N) — linear) solution in case it is acceptable for the
Positionenelements in the output to be unsorted:when this transformation is applied on the provided XML document:
the wanted, correct result is produced:
Do Note:
Every Path is produced by adding the current
IDto the path of the parent (which is calculated only once) — an O(1) operation. Fot the total of N paths this is O(N).The final sorting makes the time complexity O(N*log(N)) — still much better than quadratical.