1 package net.sf.saxon.functions; 2 import net.sf.saxon.expr.XPathContext; 3 import net.sf.saxon.om.Item; 4 import net.sf.saxon.om.SequenceIterator; 5 import net.sf.saxon.trans.XPathException; 6 import net.sf.saxon.value.AtomicValue; 7 import net.sf.saxon.value.NumericValue; 8 9 12 13 14 public class Insert extends SystemFunction { 15 16 19 20 public SequenceIterator iterate(XPathContext context) throws XPathException { 21 SequenceIterator seq = argument[0].iterate(context); 22 AtomicValue n0 = (AtomicValue)argument[1].evaluateItem(context); 23 NumericValue n = (NumericValue)n0.getPrimitiveValue(); 24 int pos = (int)n.longValue(); 25 SequenceIterator ins = argument[2].iterate(context); 26 return new InsertIterator(seq, ins, pos); 27 } 28 29 public static class InsertIterator implements SequenceIterator { 30 31 private SequenceIterator base; 32 private SequenceIterator insert; 33 private int insertPosition; 34 private int position = 0; 35 private Item current = null; 36 private boolean inserting = false; 37 38 public InsertIterator(SequenceIterator base, SequenceIterator insert, int insertPosition) { 39 this.base = base; 40 this.insert = insert; 41 this.insertPosition = (insertPosition<1 ? 1 : insertPosition); 42 this.inserting = (insertPosition==1); 43 } 44 45 46 public Item next() throws XPathException { 47 Item nextItem; 48 if (inserting) { 49 nextItem = insert.next(); 50 if (nextItem == null) { 51 inserting = false; 52 nextItem = base.next(); 53 } 54 } else { 55 if (position == insertPosition-1) { 56 nextItem = insert.next(); 57 if (nextItem == null) { 58 nextItem = base.next(); 59 } else { 60 inserting = true; 61 } 62 } else { 63 nextItem = base.next(); 64 if (nextItem==null && position < insertPosition-1) { 65 inserting = true; 66 nextItem = insert.next(); 67 } 68 } 69 } 70 if (nextItem == null) { 71 current = null; 72 position = -1; 73 return null; 74 } else { 75 current = nextItem; 76 position++; 77 return current; 78 } 79 } 80 81 public Item current() { 82 return current; 83 } 84 85 public int position() { 86 return position; 87 } 88 89 public SequenceIterator getAnother() throws XPathException { 90 return new InsertIterator( base.getAnother(), 91 insert.getAnother(), 92 insertPosition); 93 } 94 95 104 105 public int getProperties() { 106 return 0; 107 } 108 109 } 110 111 } 112 113 114 115 116 | Popular Tags |