下面列出了怎么用org.xml.sax.SAXException的API类实例代码及写法,或者点击链接到github查看源代码。
public static String[] readTitleAuthor() {
String result[] = new String[2];
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setValidating(false);
DocumentBuilder db;
Document doc;
try {
File fXmlFile = new File(org.buildmlearn.toolkit.flashcardtemplate.Constants.XMLFileName);
db = dbf.newDocumentBuilder();
doc = db.parse(fXmlFile);
doc.normalize();
result[0] = doc.getElementsByTagName("title").item(0).getChildNodes()
.item(0).getNodeValue();
result[1] = doc.getElementsByTagName("name").item(0).getChildNodes()
.item(0).getNodeValue();
} catch (ParserConfigurationException | SAXException | IOException e) {
e.printStackTrace();
}
return result;
}
public void enterElement(String $__uri, String $__local, String $__qname, Attributes $attrs) throws SAXException {
int $ai;
$uri = $__uri;
$localName = $__local;
$qname = $__qname;
switch($_ngcc_current_state) {
case 0:
{
revertToParentFromEnterElement(makeResult(), super._cookie, $__uri, $__local, $__qname, $attrs);
}
break;
default:
{
unexpectedEnterElement($__qname);
}
break;
}
}
private void processNamespaceAttribute(String prefix, String uri) throws SAXException {
_contentHandler.startPrefixMapping(prefix, uri);
if (_namespacePrefixesFeature) {
// Add the namespace delcaration as an attribute
if (prefix != "") {
_attributes.addAttributeWithQName(XMLConstants.XMLNS_ATTRIBUTE_NS_URI, prefix,
getQName(XMLConstants.XMLNS_ATTRIBUTE, prefix),
"CDATA", uri);
} else {
_attributes.addAttributeWithQName(XMLConstants.XMLNS_ATTRIBUTE_NS_URI, XMLConstants.XMLNS_ATTRIBUTE,
XMLConstants.XMLNS_ATTRIBUTE,
"CDATA", uri);
}
}
cacheNamespacePrefix(prefix);
}
/**
* Writes the whole envelope as SAX events.
*/
@Override
public void writeTo( ContentHandler contentHandler, ErrorHandler errorHandler ) throws SAXException {
String soapNsUri = soapVersion.nsUri;
contentHandler.setDocumentLocator(NULL_LOCATOR);
contentHandler.startDocument();
contentHandler.startPrefixMapping("S",soapNsUri);
contentHandler.startElement(soapNsUri,"Envelope","S:Envelope",EMPTY_ATTS);
if(hasHeaders()) {
contentHandler.startElement(soapNsUri,"Header","S:Header",EMPTY_ATTS);
MessageHeaders headers = getHeaders();
for (Header h : headers.asList()) {
h.writeTo(contentHandler,errorHandler);
}
contentHandler.endElement(soapNsUri,"Header","S:Header");
}
// write the body
contentHandler.startElement(soapNsUri,"Body","S:Body",EMPTY_ATTS);
writePayloadTo(contentHandler,errorHandler, true);
contentHandler.endElement(soapNsUri,"Body","S:Body");
contentHandler.endElement(soapNsUri,"Envelope","S:Envelope");
}
/**
* Returns a DOM object representing parsed xml.
*
* @param xml The xml to parse
* @return Parsed XML document
*/
private static Document parse(String xml)
throws IOException, ParserConfigurationException, SAXException {
ErrorHandler errors = new ErrorHandler();
try {
synchronized (factory) {
DocumentBuilder builder = factory.newDocumentBuilder();
builder.setErrorHandler(errors);
return builder.parse(new InputSource(new StringReader(xml)));
}
} catch (SAXException se) {
// Prefer parse errors over general errors.
errors.throwIfErrors();
throw se;
}
}
public void joinByText( NGCCEventReceiver source,
String value ) throws SAXException {
if(isJoining) return; // we are already in the process of joining. ignore.
isJoining = true;
// send special token to the rest of the branches.
// these branches don't understand this token, so they will
// try to move to a final state and send the token back to us,
// which this object will ignore (because isJoining==true)
// Otherwise branches will find an error.
for( int i=0; i<_receivers.length; i++ )
if( _receivers[i]!=source )
_receivers[i].text(value);
// revert to the parent
_parent._source.replace(this,_parent);
_parent.onChildCompleted(null,_cookie,true);
// send this event to the parent
_parent.text(value);
}
@Override
public void startElement(final String pUri, final String pLocalName, final String pQualifiedName, final Attributes pAttributes) throws SAXException {
final String entityName = pLocalName;
final IEntity parent = (this.mParentEntityStack.isEmpty()) ? null : this.mParentEntityStack.getLast();
final IEntityLoader entityLoader = this.mEntityLoaders.get(entityName);
final IEntity entity;
if(entityLoader != null) {
entity = entityLoader.onLoadEntity(entityName, pAttributes);
} else if(this.mDefaultEntityLoader != null) {
entity = this.mDefaultEntityLoader.onLoadEntity(entityName, pAttributes);
} else {
throw new IllegalArgumentException("Unexpected tag: '" + entityName + "'.");
}
if(parent != null && entity != null) {
parent.attachChild(entity);
}
this.mParentEntityStack.addLast(entity);
}
private void processNamespaceAttribute(String prefix, String uri) throws SAXException {
_contentHandler.startPrefixMapping(prefix, uri);
if (_namespacePrefixesFeature) {
// Add the namespace delcaration as an attribute
if (prefix != "") {
_attributes.addAttributeWithQName(XMLConstants.XMLNS_ATTRIBUTE_NS_URI, prefix,
getQName(XMLConstants.XMLNS_ATTRIBUTE, prefix),
"CDATA", uri);
} else {
_attributes.addAttributeWithQName(XMLConstants.XMLNS_ATTRIBUTE_NS_URI, XMLConstants.XMLNS_ATTRIBUTE,
XMLConstants.XMLNS_ATTRIBUTE,
"CDATA", uri);
}
}
cacheNamespacePrefix(prefix);
}
private SAXException log(String errorType, SAXParseException e) {
Level level;
String message;
if (file == null) {
level = Level.FINE;
message = "XML parser " + errorType;
} else {
if (isModuleFile()) { //NOI18N
level = Level.WARNING; // warnings for module layer supplied files
} else {
level = Level.FINE; // user files, can be from previous versions
}
message = "XML parser " + errorType + " in file " + file.getPath();
}
SAXException saxe = new SAXException(message);
saxe.initCause(e);
LOG.log(level, message, saxe); //NOI18N
return saxe;
}
@Test
public void testConfig() throws SAXException, IOException {
String dataSourceResourceId = "sample.ds.v2";
Map<String, Object> configs = ServiceConfigBuilder.newInstance()
.putValue(Constants.CONFIG_SERVICE_NAME_KEY, dataSourceResourceId).build();
ConfigService configService = ConfigServiceFactory.getConfigService(Constants.CONFIG_MANAGER_TYPE_LOCAL, configs);
DataSourceConfigManager dataSourceConfigManager = DataSourceConfigManagerFactory
.getConfigManager(dataSourceResourceId, configService);
Map<String, DataSourceConfig> config = dataSourceConfigManager.getGroupDataSourceConfig().getDataSourceConfigs();
Map<String, DataSourceConfig> dataSourceConfigs = DefaultSaxParser
.parse(getClass().getClassLoader().getResourceAsStream("model/datasources.xml")).getDataSourceConfigs();
for (DataSourceConfig entry : config.values()) {
DataSourceConfig dataSourceConfig = dataSourceConfigs.get(entry.getId());
Assert.assertEquals(dataSourceConfig.toString(), entry.toString());
}
}
public void testLoadXML10Model() throws ParserConfigurationException, SAXException, IOException,
TransformerException {
XMLUtils theUtils = XMLUtils.getInstance();
DocumentBuilderFactory theFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder theBuilder = theFactory.newDocumentBuilder();
Document theDoc = theBuilder.parse(getClass().getResourceAsStream("examplemodel.mxm"));
AbstractXMLModelSerializer theSerializer = new XMLModel10Serializer(theUtils);
Model theModel = theSerializer.deserializeModelFromXML(theDoc);
StringWriter theStringWriter = new StringWriter();
theSerializer.serializeModelToXML(theModel, theStringWriter);
String theOriginalFile = readResourceFile("examplemodel.mxm");
String theNewFile = theStringWriter.toString();
assertTrue(compareStrings(theOriginalFile, theNewFile));
}
/**
* Parses a {@link DOMForest} into a {@link XSSchemaSet}.
*
* @return
* null if the parsing failed.
*/
public XSSchemaSet createXSOM(DOMForest forest, SCDBasedBindingSet scdBasedBindingSet) throws SAXException {
// set up other parameters to XSOMParser
XSOMParser reader = createXSOMParser(forest);
// re-parse the transformed schemas
for (String systemId : forest.getRootDocuments()) {
errorReceiver.pollAbort();
Document dom = forest.get(systemId);
if (!dom.getDocumentElement().getNamespaceURI().equals(Const.JAXB_NSURI)) {
reader.parse(systemId);
}
}
XSSchemaSet result = reader.getResult();
if(result!=null)
scdBasedBindingSet.apply(result,errorReceiver);
return result;
}
/**
* Read a {@link File} into an {@link OpenImmoTransferDocument} or
* {@link OpenImmoFeedbackDocument} and print some of their content to
* console.
*
* @param xmlFile the file to read
* @throws SAXException if the file is not readable by the XML parser
* @throws IOException if the file is not readable
* @throws ParserConfigurationException if the XML parser is improperly configured
* @throws JAXBException if XML conversion into Java objects failed
*/
@SuppressWarnings("Duplicates")
protected static void read(File xmlFile) throws SAXException, IOException, ParserConfigurationException, JAXBException {
LOGGER.info("process file: " + xmlFile.getAbsolutePath());
if (!xmlFile.isFile()) {
LOGGER.warn("> provided file is invalid");
return;
}
OpenImmoDocument doc = OpenImmoUtils.createDocument(xmlFile);
if (doc == null) {
LOGGER.warn("> provided XML is not supported");
} else if (doc.isFeedback()) {
printToConsole((OpenImmoFeedbackDocument) doc);
} else if (doc.isTransfer()) {
printToConsole((OpenImmoTransferDocument) doc);
} else {
LOGGER.warn("> unsupported type of document: "
+ doc.getClass().getName());
}
}
public void testParseXml() throws ParserConfigurationException, IOException, SAXException {
// This is a small test of the configuration parsing developed when upgrading the xstream library.
BaseConfigurationService configurationService = new BaseConfigurationService();
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(false);
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document document = builder.parse(getClass().getResourceAsStream("config-example.xml"));
configurationService.saveServletClientMappings(document);
Map<String, List<Map<String, String>>> saveciteClients = configurationService.getSaveciteClients();
assertEquals(1, saveciteClients.size());
List<Map<String, String>> en = saveciteClients.get("en");
assertNotNull(en);
Map<String, String> first = en.get(0);
assertNotNull(first);
assertEquals("Test", first.get("test"));
assertEquals("saveciteClients", first.get("id"));
}
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if (fault) {
return;
}
switch (qName) {
case "fault":
fault = true;
break;
case "member":
currentMemberName = null;
currentMemberValue = null;
break;
case "name":
currentCharacters = new StringBuilder();
break;
case "string":
currentCharacters = new StringBuilder();
break;
case "boolean":
currentCharacters = new StringBuilder();
break;
default:
// empty
}
}
/**
* Creates a new instance of a {@link javax.xml.parsers.DocumentBuilder}
* using the currently configured parameters.
*/
public DocumentBuilder newDocumentBuilder()
throws ParserConfigurationException
{
/** Check that if a Schema has been specified that neither of the schema properties have been set. */
if (grammar != null && attributes != null) {
if (attributes.containsKey(JAXPConstants.JAXP_SCHEMA_LANGUAGE)) {
throw new ParserConfigurationException(
SAXMessageFormatter.formatMessage(null,
"schema-already-specified", new Object[] {JAXPConstants.JAXP_SCHEMA_LANGUAGE}));
}
else if (attributes.containsKey(JAXPConstants.JAXP_SCHEMA_SOURCE)) {
throw new ParserConfigurationException(
SAXMessageFormatter.formatMessage(null,
"schema-already-specified", new Object[] {JAXPConstants.JAXP_SCHEMA_SOURCE}));
}
}
try {
return new DocumentBuilderImpl(this, attributes, features, fSecureProcess);
} catch (SAXException se) {
// Handles both SAXNotSupportedException, SAXNotRecognizedException
throw new ParserConfigurationException(se.getMessage());
}
}
@Override
public void endElement (final String uri, final String localName, final String qName) throws SAXException {
final String elementName = !localName.isEmpty() ? localName : qName;
if (this.stack.size() == 3) { // NOSONAR not a magic number.
if ("column".equals(elementName)) {
if (!StringHelper.isEmpty(this.stashedFullpath)) {
this.columns.add(new Column(this.columns.size(), this.stashedTitle, new ColumnFeed(this.account.getId(), this.stashedFullpath), DEFAULT_COLUMN_REFRESH_MINS, null, false, null, InlineMediaStyle.NONE, false));
}
this.stashedFullpath = null;
this.stashedTitle = null;
}
}
else if (this.stack.size() == 4) { // NOSONAR not a magic number.
if ("fullpath".equals(elementName)) {
this.stashedFullpath = this.currentText.toString();
}
else if ("title".equals(elementName)) {
this.stashedTitle = this.currentText.toString();
}
}
this.stack.pop();
}
/**
* This method is used to add an attribute to the currently open element.
* The caller has guaranted that this attribute is unique, which means that it
* not been seen before and will not be seen again.
*
* @param name the qualified name of the attribute
* @param value the value of the attribute which can contain only
* ASCII printable characters characters in the range 32 to 127 inclusive.
* @param flags the bit values of this integer give optimization information.
*/
public void addUniqueAttribute(String name, String value, int flags)
throws SAXException
{
if (m_elemContext.m_startTagOpen)
{
try
{
final String patchedName = patchName(name);
final java.io.Writer writer = m_writer;
if ((flags & NO_BAD_CHARS) > 0 && m_xmlcharInfo.onlyQuotAmpLtGt)
{
// "flags" has indicated that the characters
// '>' '<' '&' and '"' are not in the value and
// m_htmlcharInfo has recorded that there are no other
// entities in the range 32 to 127 so we write out the
// value directly
writer.write(' ');
writer.write(patchedName);
writer.write("=\"");
writer.write(value);
writer.write('"');
}
else
{
writer.write(' ');
writer.write(patchedName);
writer.write("=\"");
writeAttrString(writer, value, this.getEncoding());
writer.write('"');
}
} catch (IOException e) {
throw new SAXException(e);
}
}
}
public void parse(InputSource unused) throws IOException, SAXException {
try {
bridge();
} catch (XMLStreamException e) {
throw new SAXException(e);
}
}
/**
* Gives a list of Reference Parameters in the Message
* <p>
* Headers which have attribute wsa:IsReferenceParameter="true"
* This is not cached as one may reset the Message.
*<p>
*/
@Property(MessageContext.REFERENCE_PARAMETERS)
public
@NotNull
List<Element> getReferenceParameters() {
Message msg = getMessage();
List<Element> refParams = new ArrayList<Element>();
if (msg == null) {
return refParams;
}
MessageHeaders hl = msg.getHeaders();
for (Header h : hl.asList()) {
String attr = h.getAttribute(AddressingVersion.W3C.nsUri, "IsReferenceParameter");
if (attr != null && (attr.equals("true") || attr.equals("1"))) {
Document d = DOMUtil.createDom();
SAX2DOMEx s2d = new SAX2DOMEx(d);
try {
h.writeTo(s2d, XmlUtil.DRACONIAN_ERROR_HANDLER);
refParams.add((Element) d.getLastChild());
} catch (SAXException e) {
throw new WebServiceException(e);
}
/*
DOMResult result = new DOMResult(d);
XMLDOMWriterImpl domwriter = new XMLDOMWriterImpl(result);
try {
h.writeTo(domwriter);
refParams.add((Element) result.getNode().getLastChild());
} catch (XMLStreamException e) {
throw new WebServiceException(e);
}
*/
}
}
return refParams;
}
@Override
void end() throws SAXException {
if (childPatterns == null) {
endChild(schemaBuilder.makeText(startLocation, null));
}
super.end();
}
public GraphDocument parse(XMLReader reader, InputSource source, XMLParser.ParseMonitor monitor) throws SAXException {
reader.setContentHandler(new XMLParser(xmlDocument, monitor));
try {
reader.parse(source);
} catch (IOException ex) {
throw new SAXException(ex);
}
return topHandler.getObject();
}
public void testEndDocument() {
try {
h.endDocument();
} catch (SAXException e) {
throw new RuntimeException(e);
}
}
public static <T> Object unmarshal(final Class<T> type, final InputStream in, final boolean logErrors) throws ParserConfigurationException, SAXException, JAXBException {
final InputSource inputSource = new InputSource(in);
final SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(true);
factory.setValidating(false);
final SAXParser parser = factory.newSAXParser();
final JAXBContext ctx = getContext(type);
final Unmarshaller unmarshaller = ctx.createUnmarshaller();
unmarshaller.setEventHandler(new ValidationEventHandler() {
public boolean handleEvent(final ValidationEvent validationEvent) {
if (logErrors) {
System.out.println(validationEvent);
}
return false;
}
});
unmarshaller.setListener(new Unmarshaller.Listener() {
public void afterUnmarshal(final Object object, final Object object1) {
super.afterUnmarshal(object, object1);
}
public void beforeUnmarshal(final Object target, final Object parent) {
super.beforeUnmarshal(target, parent);
}
});
final NamespaceFilter xmlFilter = new NamespaceFilter(parser.getXMLReader());
xmlFilter.setContentHandler(unmarshaller.getUnmarshallerHandler());
final SAXSource source = new SAXSource(xmlFilter, inputSource);
return unmarshaller.unmarshal(source, type);
}
public static BundleRepoDescriptor parse(URI baseUri, InputStream in) throws IOException,
SAXException {
RepositoryHandler handler = new RepositoryHandler(baseUri);
try {
XMLHelper.parse(in, null, handler, null);
} catch (ParserConfigurationException e) {
throw new SAXException(e);
}
return handler.repo;
}
public void startPrefixMapping(java.lang.String prefix, java.lang.String uri)
throws org.xml.sax.SAXException
{
if(--eventcounter<=0)
{
co_yield(true);
eventcounter=frequency;
}
if(clientContentHandler!=null)
clientContentHandler.startPrefixMapping(prefix,uri);
}
public void processingInstruction(String target, String data)
throws SAXException {
try {
staxWriter.writeProcessingInstruction(target, data);
} catch (XMLStreamException e) {
throw new SAXException(e);
}
}
private NameCacheEntry maybeGetNameCacheEntry()
throws IOException, SAXException {
// [5] Name ::= (Letter|'_'|':') (Namechar)*
char c = getc();
if (!XmlChars.isLetter(c) && c != ':' && c != '_') {
ungetc();
return null;
}
return nameCharString(c);
}
@Test
public void testReader() throws SAXException, IOException {
String xmlFileName ="D:\\works\\fm\\trade\\tables\\menu.xml";
XMLHelper xmlHelper =new XMLHelper();
// NodeData parseXML = xmlHelper.parseXML(new File(xmlFileName));
// System.out.println("parseXML<===========>:" + parseXML);
TableConfigXmlBuilder tableConfigXmlBuilder = new TableConfigXmlBuilder();
tableConfigXmlBuilder.parseFromXML(new File(xmlFileName));
}
/**
* Implements org.xml.sax.DTDHandler.unparsedEntityDecl()
*/
@Override
public void unparsedEntityDecl(String name, String publicId,
String systemId, String notationName) throws SAXException
{
if (_dtdHandler != null) {
_dtdHandler.unparsedEntityDecl(name, publicId, systemId,
notationName);
}
}