view software/mpdl-services/mpiwg-mpdl-xml/src/de/mpg/mpiwg/berlin/mpdl/xml/tmp/GetFragmentContentHandler.java @ 18:dc5e9fcb3fdc

Erstellung
author Josef Willenborg <jwillenborg@mpiwg-berlin.mpg.de>
date Wed, 09 Nov 2011 15:27:46 +0100
parents
children
line wrap: on
line source

package de.mpg.mpiwg.berlin.mpdl.xml.tmp;

import org.xml.sax.*;

public class GetFragmentContentHandler implements ContentHandler {
  private String ms1Name;
  private String ms2Name;
  private int ms1Pos; 
  private int ms2Pos;
  
  private int msCounter = 1;
  private boolean startFragment = false;
  private String fragment = "";
  
  public GetFragmentContentHandler(String ms1Name, int ms1Pos, String ms2Name, int ms2Pos) {
    this.ms1Name = ms1Name;
    this.ms2Name = ms2Name;
    this.ms1Pos = ms1Pos;
    this.ms2Pos = ms2Pos;
  }
  
  public void startDocument() throws SAXException {
    fragment += "<?xml version=\"1.0\"?>\n";
  }

  public void endDocument() throws SAXException {
  }
  
  public void characters(char[] c, int start, int length) throws SAXException {
    if (startFragment) {
      char[] cCopy = new char[length];
      System.arraycopy(c, start, cCopy, 0, length);
      String charactersStr = String.valueOf(cCopy);
      if (charactersStr != null && ! (charactersStr.trim().equals(""))) {
        fragment += charactersStr;
      }
    }
  }

  public void ignorableWhitespace(char[] c, int start, int length) throws SAXException {
  }

  public void processingInstruction(String target, String data) throws SAXException {
  }

  public void setDocumentLocator(org.xml.sax.Locator arg1) {
  }

  public void endPrefixMapping(String prefix) throws SAXException {
  }

  public void skippedEntity(String name) throws SAXException {
  }

  public void startElement(String uri, String localName, String name, Attributes attrs) throws SAXException {
    if (localName.equals(ms1Name)) {
      if (msCounter == ms1Pos) {
        startFragment = true;
      }
      if (msCounter == ms2Pos) {
        startFragment = false;
        throw new SAXException("end");
      }
      msCounter++;
    }
    if (startFragment) {
      fragment += "<" + name;
      int attrSize = attrs.getLength();
      String attrString = "";
      for (int i=0; i<attrSize; i++) {
        String attrQName = attrs.getQName(i);
        String attrValue = attrs.getValue(i);
        // attrValue = StringUtilEscapeChars.forXML(attrValue);
        attrString = attrString + " " + attrQName + "=\"" + attrValue + "\"";
      }
      fragment += attrString + ">";
    }
  }

  public void endElement(String uri, String localName, String name) throws SAXException {
    if (startFragment) {
      fragment += "</" + name + ">";
    }
  }

  public void startPrefixMapping(String prefix, String uri) throws SAXException {
  }
  
  public String getFragment() {
    return fragment;  
  }
  
}