NamedChildrenFilter.java 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. // Copyright (c) 2002 Per M.A. Bothner and Brainfood Inc.
  2. // This is free software; for terms and warranty disclaimer see ./COPYING.
  3. package gnu.xml;
  4. import gnu.lists.*;
  5. import gnu.mapping.Symbol;
  6. /** A FilterConsumer that only passes through matching children.
  7. */
  8. public class NamedChildrenFilter extends FilterConsumer
  9. {
  10. String namespaceURI;
  11. String localName;
  12. int level;
  13. int matchLevel;
  14. public static NamedChildrenFilter
  15. make (String namespaceURI, String localName, Consumer out)
  16. {
  17. return new NamedChildrenFilter(namespaceURI, localName, out);
  18. }
  19. public NamedChildrenFilter (String namespaceURI, String localName,
  20. Consumer out)
  21. {
  22. super(out);
  23. this.namespaceURI = namespaceURI;
  24. this.localName = localName;
  25. skipping = true;
  26. }
  27. public void startDocument()
  28. {
  29. level++;
  30. super.startDocument();
  31. }
  32. public void endDocument()
  33. {
  34. level--;
  35. super.endDocument();
  36. }
  37. public void startElement (Object type)
  38. {
  39. if (skipping && level == 1 // && axis is child::
  40. // || axis is descdendent-or-self::
  41. // || level >= 1 && axis is descdendent
  42. )
  43. {
  44. String curNamespaceURI;
  45. String curLocalName;
  46. if (type instanceof Symbol)
  47. {
  48. Symbol qname = (Symbol) type;
  49. curNamespaceURI = qname.getNamespaceURI();
  50. curLocalName = qname.getLocalName();
  51. }
  52. else
  53. {
  54. curNamespaceURI = "";
  55. curLocalName = type.toString().intern(); // FIXME
  56. }
  57. if ((localName == curLocalName || localName == null)
  58. && (namespaceURI == curNamespaceURI || namespaceURI == null))
  59. {
  60. skipping = false;
  61. matchLevel = level;
  62. }
  63. }
  64. super.startElement(type);
  65. level++;
  66. }
  67. public void endElement ()
  68. {
  69. level--;
  70. super.endElement();
  71. if (! skipping && matchLevel == level)
  72. skipping = true;
  73. }
  74. public void writeObject(Object val)
  75. {
  76. if (val instanceof SeqPosition)
  77. {
  78. SeqPosition pos = (SeqPosition) val;
  79. if (pos.sequence instanceof TreeList)
  80. {
  81. ((TreeList) pos.sequence).consumeNext(pos.ipos, this);
  82. return;
  83. }
  84. }
  85. if (val instanceof Consumable)
  86. ((Consumable) val).consume(this);
  87. else
  88. super.writeObject(val);
  89. }
  90. }