下面列出了怎么用org.xml.sax.ContentHandler的API类实例代码及写法,或者点击链接到github查看源代码。
protected void export(TopicRoleConstraint constraint, ContentHandler dh)
throws SAXException {
dh.startElement("", "", "playing", getMinMax(constraint));
exportInstanceOf(constraint.getTypeSpecification(), dh);
Iterator it = constraint.getAssociationTypes().iterator();
if (it.hasNext()) {
dh.startElement("", "", "in", EMPTY_ATTR_LIST);
while (it.hasNext()) {
TypeSpecification spec = (TypeSpecification) it.next();
exportInstanceOf(spec, dh);
}
dh.endElement("", "", "in");
}
dh.endElement("", "", "playing");
}
/**
* Parse one document off of the incoming XTalk stream into SAX events. A side effect of parsing
* is that internal arrays will grow to the size of the largest character string encountered in
* the document. Use bufferSize() and resizeBuffers to manage memory in applications where very
* large strings may be encountered and the same object is used to parse many incoming documents.
*
* @param is -
* @param handler -
* @throws IOException
* if underlying IOException from the stream or if XTalk format is invalid.
* @throws SAXException
* if SAXException thrown by the handler
*
* @pre handler != null
* @pre is != null
*/
public void parse(InputStream is, ContentHandler handler) throws IOException, SAXException {
this.is = is;
this.handler = handler;
try {
int marker = is.read();
if (marker == -1) {
throw new EOFException();
}
if ((byte) marker != XTalkTransporter.DOCUMENT_MARKER) {
throw new IOException("Expected document marker: " + (char) marker);
}
int version = is.read();
if ((byte) version != XTalkTransporter.VERSION_CODE) {
throw new IOException("Xtalk version code doesn't match "
+ (int) XTalkTransporter.VERSION_CODE + ": " + version);
}
handler.startDocument();
doTopLevelParse();
handler.endDocument();
} finally {
// nullify refs to allow GC
is = null;
handler = null;
}
}
public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException {
ContentHandler[] arr$ = this.handlers;
int len$ = arr$.length;
for(int i$ = 0; i$ < len$; ++i$) {
ContentHandler handler = arr$[i$];
handler.ignorableWhitespace(ch, start, length);
}
}
@Override
protected void toXml(ContentHandler contentHandler) throws SAXException {
XMLUtils.addSaxString(contentHandler, "LENGTH",
Integer.toString(length));
XMLUtils.addSaxString(contentHandler, "SRC", src);
XMLUtils.addSaxString(contentHandler, "DST", dst);
XMLUtils.addSaxString(contentHandler, "TIMESTAMP",
Long.toString(timestamp));
appendRpcIdsToXml(contentHandler, rpcClientId, rpcCallId);
}
/**
* @param outputStream The output
* @return A content handler
* @throws IOException When there's an XML error
*/
private ContentHandler createContentHandler(OutputStream outputStream) throws IOException {
Properties outputProperties = OutputPropertiesFactory.getDefaultMethodProperties(Method.XML);
outputProperties.setProperty("indent", "yes");
outputProperties.setProperty(OutputPropertiesFactory.S_KEY_INDENT_AMOUNT, "2");
outputProperties.setProperty(OutputPropertiesFactory.S_KEY_LINE_SEPARATOR, "\n");
Serializer serializer = SerializerFactory.getSerializer(outputProperties);
serializer.setOutputStream(outputStream);
return serializer.asContentHandler();
}
public void endDocument() throws SAXException {
ContentHandler[] arr$ = this.handlers;
int len$ = arr$.length;
for(int i$ = 0; i$ < len$; ++i$) {
ContentHandler handler = arr$[i$];
handler.endDocument();
}
}
/**
* @since 2.0.2
*/
public final void marshal(T object, ContentHandler contentHandler, AttachmentMarshaller am) throws JAXBException {
Marshaller m = context.marshallerPool.take();
m.setAttachmentMarshaller(am);
marshal(m,object,contentHandler);
m.setAttachmentMarshaller(null);
context.marshallerPool.recycle(m);
}
@Test
public void contentHandlerNoNamespacesPrefixes() throws Exception {
standardReader.setFeature("http://xml.org/sax/features/namespaces", false);
standardReader.setFeature("http://xml.org/sax/features/namespace-prefixes", true);
standardReader.parse(new InputSource(createTestInputStream()));
AbstractStaxXMLReader staxXmlReader = createStaxXmlReader(createTestInputStream());
ContentHandler contentHandler = mockContentHandler();
staxXmlReader.setFeature("http://xml.org/sax/features/namespaces", false);
staxXmlReader.setFeature("http://xml.org/sax/features/namespace-prefixes", true);
staxXmlReader.setContentHandler(contentHandler);
staxXmlReader.parse(new InputSource());
verifyIdenticalInvocations(standardContentHandler, contentHandler);
}
protected void exportInstanceOf(TypeSpecification spec, ContentHandler dh)
throws SAXException {
dh.startElement("", "", "instanceOf", getAttributes(spec.getSubclasses(),
"subclasses", "yes", "no"));
export(spec.getClassMatcher(), dh);
dh.endElement("", "", "instanceOf");
}
private static void appendAclEntriesToXml(ContentHandler contentHandler,
List<AclEntry> aclEntries) throws SAXException {
for (AclEntry e : aclEntries) {
contentHandler.startElement("", "", "ENTRY", new AttributesImpl());
XMLUtils.addSaxString(contentHandler, "SCOPE", e.getScope().name());
XMLUtils.addSaxString(contentHandler, "TYPE", e.getType().name());
if (e.getName() != null) {
XMLUtils.addSaxString(contentHandler, "NAME", e.getName());
}
fsActionToXml(contentHandler, e.getPermission());
contentHandler.endElement("", "", "ENTRY");
}
}
public ToXMLSAXHandler(
ContentHandler handler,
LexicalHandler lex,
String encoding)
{
super(handler, lex, encoding);
initCDATA();
// initNamespaces();
m_prefixMap = new NamespaceMappings();
}
protected void export(TopicClass klass, ContentHandler dh)
throws SAXException {
AttributesImpl atts =
(AttributesImpl) getAttributes(klass.isStrict(),
"match", "strict", "loose");
if (klass.getId() != null)
atts.addAttribute("", "", "id", "CDATA", klass.getId());
dh.startElement("", "", "topic", atts);
exportInstanceOf(klass.getTypeSpecification(), dh);
// otherClass
Iterator it = klass.getOtherClasses().iterator();
while (it.hasNext()) {
TypeSpecification typespec = (TypeSpecification) it.next();
dh.startElement("", "", "otherClass", EMPTY_ATTR_LIST);
export(typespec.getClassMatcher(), dh);
dh.endElement("", "", "otherClass");
}
// superclass
if (klass.getSuperclass() != null) {
TopicClass superclass = klass.getSuperclass();
// FIXME: what if no id?
dh.startElement("", "", "superclass", getAttributes("ref", superclass.getId()));
dh.endElement("", "", "superclass");
}
export((TopicConstraintCollection) klass, dh);
dh.endElement("", "", "topic");
}
@Test
public void partial() throws Exception {
XMLInputFactory inputFactory = XMLInputFactory.newInstance();
XMLEventReader eventReader = inputFactory.createXMLEventReader(new StringReader(CONTENT));
eventReader.nextTag(); // skip to root
StaxEventXMLReader xmlReader = new StaxEventXMLReader(eventReader);
ContentHandler contentHandler = mock(ContentHandler.class);
xmlReader.setContentHandler(contentHandler);
xmlReader.parse(new InputSource());
verify(contentHandler).startDocument();
verify(contentHandler).startElement(eq("http://springframework.org/spring-ws"), eq("child"), eq("child"), any(Attributes.class));
verify(contentHandler).endElement("http://springframework.org/spring-ws", "child", "child");
verify(contentHandler).endDocument();
}
public void processingInstruction(String target, String data) throws SAXException {
ContentHandler[] arr$ = this.handlers;
int len$ = arr$.length;
for(int i$ = 0; i$ < len$; ++i$) {
ContentHandler handler = arr$[i$];
handler.processingInstruction(target, data);
}
}
/**
* @since 2.0.2
*/
public final void marshal(T object, ContentHandler contentHandler, AttachmentMarshaller am) throws JAXBException {
Marshaller m = context.marshallerPool.take();
m.setAttachmentMarshaller(am);
marshal(m,object,contentHandler);
m.setAttachmentMarshaller(null);
context.marshallerPool.recycle(m);
}
/**
* PUBLIC: Exports a set of topics without any wrapping element.
*/
public void exportTopics(Iterator it, ContentHandler dh) throws SAXException {
while (it.hasNext()) {
TopicIF topic = (TopicIF) it.next();
if (filterOk(topic))
writeTopic(topic, dh);
}
}
@Override
public void toXML(ContentHandler aContentHandler, boolean aWriteDefaultNamespaceAttribute)
throws SAXException {
XmlizationInfo inf = getXmlizationInfo();
// write the element's start tag
// get attributes (can be provided by subclasses)
AttributesImpl attrs = getXMLAttributes();
// add default namespace attr if desired
if (aWriteDefaultNamespaceAttribute) {
if (inf.namespace != null) {
attrs.addAttribute("", "xmlns", "xmlns", null, inf.namespace);
}
}
// start element
aContentHandler.startElement(inf.namespace, inf.elementTagName, inf.elementTagName, attrs);
// write child elements
for (int i = 0; i < casProcessors.size(); i++) {
((CpeCasProcessor) casProcessors.get(i)).toXML(aContentHandler,
aWriteDefaultNamespaceAttribute);
}
// end element
aContentHandler.endElement(inf.namespace, inf.elementTagName, inf.elementTagName);
}
private void endPrefixMapping(ContentHandler contentHandler, NamedNodeMap attrs, String excludePrefix) throws SAXException {
if(attrs == null)
return;
for(int i=0; i < attrs.getLength();i++) {
Attr a = (Attr)attrs.item(i);
//check if attr is ns declaration
if("xmlns".equals(a.getPrefix()) || "xmlns".equals(a.getLocalName())) {
if(!fixNull(a.getPrefix()).equals(excludePrefix)) {
contentHandler.endPrefixMapping(fixNull(a.getPrefix()));
}
}
}
}
public void startPrefixMapping(String prefix, String uri) throws SAXException {
ContentHandler[] arr$ = this.handlers;
int len$ = arr$.length;
for(int i$ = 0; i$ < len$; ++i$) {
ContentHandler handler = arr$[i$];
handler.startPrefixMapping(prefix, uri);
}
}
@Override
protected void toXml(ContentHandler contentHandler) throws SAXException {
XMLUtils.addSaxString(contentHandler, "SNAPSHOTROOT", snapshotRoot);
XMLUtils.addSaxString(contentHandler, "SNAPSHOTOLDNAME", snapshotOldName);
XMLUtils.addSaxString(contentHandler, "SNAPSHOTNEWNAME", snapshotNewName);
appendRpcIdsToXml(contentHandler, rpcClientId, rpcCallId);
}
public void setContentHandler(ContentHandler handler) throws
NullPointerException
{
_sax = handler;
if (handler instanceof LexicalHandler) {
_lex = (LexicalHandler) handler;
}
if (handler instanceof SAXImpl) {
_saxImpl = (SAXImpl)handler;
}
}
/**
* Perform Swing-HTML-parse-event-to-Sax-event conversion
*/
public void parse(Reader reader, ContentHandler saxContentHandler)
throws SAXException, IOException {
this.saxContentHandler = saxContentHandler;
preParse();
delegator.parse(reader, this, IGNORE_HTML_CHAR_SET);
postParse();
}
/**
* Basic text extraction.
* <p>
* Tries to close input stream after processing.
*/
public String getText(InputStream is, Parser parser, ParseContext context, Metadata metadata) throws Exception{
ContentHandler handler = new BodyContentHandler(1000000);
try {
parser.parse(is, handler, metadata, context);
} finally {
is.close();
}
return handler.toString();
}
/**
* Pop, or undeclare all namespace definitions that are currently
* declared at the given element depth, or deepter.
* @param elemDepth the element depth for which mappings declared at this
* depth or deeper will no longer be valid
* @param saxHandler The ContentHandler to notify of any endPrefixMapping()
* calls. This parameter can be null.
*/
void popNamespaces(int elemDepth, ContentHandler saxHandler)
{
while (true)
{
if (m_nodeStack.isEmpty())
return;
MappingRecord map = (MappingRecord)(m_nodeStack.peek());
int depth = map.m_declarationDepth;
if (depth < elemDepth)
return;
/* the depth of the declared mapping is elemDepth or deeper
* so get rid of it
*/
map = (MappingRecord) m_nodeStack.pop();
final String prefix = map.m_prefix;
popNamespace(prefix);
if (saxHandler != null)
{
try
{
saxHandler.endPrefixMapping(prefix);
}
catch (SAXException e)
{
// not much we can do if they aren't willing to listen
}
}
}
}
public void setContentHandler(ContentHandler handler) throws
NullPointerException
{
_sax = handler;
if (handler instanceof LexicalHandler) {
_lex = (LexicalHandler) handler;
}
if (handler instanceof SAXImpl) {
_saxImpl = (SAXImpl)handler;
}
}
/**
* Generates the whole set of SAX events by treating
* element e as if it's a root element.
*/
public void scan( Element e, ContentHandler contentHandler ) throws SAXException {
DOMScanner scanner = new DOMScanner();
// insert the location resolver into the pipe line
LocationResolver resolver = new LocationResolver(scanner);
resolver.setContentHandler(contentHandler);
// parse this DOM.
scanner.setContentHandler(resolver);
scanner.scan(e);
}
/**
* Parses and shows the content of one sheet using the specified styles and
* shared-strings tables.
*
* @param styles
* @param strings
* @param sheetInputStream
*/
public void processSheet(StylesTable styles, ReadOnlySharedStringsTable strings, SheetContentsHandler sheetHandler,
InputStream sheetInputStream) throws IOException, ParserConfigurationException, SAXException {
DataFormatter formatter = new DataFormatter();
InputSource sheetSource = new InputSource(sheetInputStream);
try {
XMLReader sheetParser = SAXHelper.newXMLReader();
ContentHandler handler = new XSSFSheetXMLHandler(styles, null, strings, sheetHandler, formatter, false);
sheetParser.setContentHandler(handler);
sheetParser.parse(sheetSource);
} catch (ParserConfigurationException e) {
throw new RuntimeException("SAX parser appears to be broken - " + e.getMessage());
}
}
private static XMLReader getXMLReader(Resource classloaderProvider, ContentHandler handler) throws ParserConfigurationException, SAXException {
XMLReader xmlReader = getXMLReader(true, classloaderProvider);
xmlReader.setContentHandler(handler);
if (handler instanceof LexicalHandler) {
xmlReader.setProperty("http://xml.org/sax/properties/lexical-handler", handler);
}
if (handler instanceof ErrorHandler) {
xmlReader.setErrorHandler((ErrorHandler)handler);
}
return xmlReader;
}
public void setContentHandler(final ContentHandler handler) {
contentHandler = handler;
}
public SaxSerializer(ContentHandler handler) {
this(handler,null,true);
}