下面列出了java.io.StringBufferInputStream#javax.xml.parsers.SAXParser 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public Document loadDocument(InputSource inputSource, EntityResolver entityResolver,
ErrorHandler errorHandler, int validationMode, boolean namespaceAware)
throws Exception {
if (validationMode == XmlBeanDefinitionReader.VALIDATION_NONE) {
SAXParserFactory parserFactory =
namespaceAware ? nsasaxParserFactory : saxParserFactory;
SAXParser parser = parserFactory.newSAXParser();
XMLReader reader = parser.getXMLReader();
reader.setEntityResolver(entityResolver);
reader.setErrorHandler(errorHandler);
SAXSource saxSource = new SAXSource(reader, inputSource);
W3CDOMStreamWriter writer = new W3CDOMStreamWriter();
StaxUtils.copy(saxSource, writer);
return writer.getDocument();
}
return super.loadDocument(inputSource, entityResolver, errorHandler, validationMode,
namespaceAware);
}
/**
* Reads a {@link CategoryDataset} from a stream.
*
* @param in the stream.
*
* @return A dataset.
*
* @throws IOException if there is a problem reading the file.
*/
public static CategoryDataset readCategoryDatasetFromXML(InputStream in)
throws IOException {
CategoryDataset result = null;
SAXParserFactory factory = SAXParserFactory.newInstance();
try {
SAXParser parser = factory.newSAXParser();
CategoryDatasetHandler handler = new CategoryDatasetHandler();
parser.parse(in, handler);
result = handler.getDataset();
}
catch (SAXException e) {
System.out.println(e.getMessage());
}
catch (ParserConfigurationException e2) {
System.out.println(e2.getMessage());
}
return result;
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
try {
SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
saxParserFactory.setNamespaceAware(true);
SAXParser saxParser = saxParserFactory.newSAXParser();
ParserVocabulary referencedVocabulary = new ParserVocabulary();
VocabularyGenerator vocabularyGenerator = new VocabularyGenerator(referencedVocabulary);
File f = new File(args[0]);
saxParser.parse(f, vocabularyGenerator);
printVocabulary(referencedVocabulary);
} catch (Exception e) {
e.printStackTrace();
}
}
public ArrayList<BeerStyle> getStylesFromXml(String filePath) throws IOException {
ArrayList<BeerStyle> list = new ArrayList<BeerStyle>();
BeerXmlReader myXMLHandler = new BeerXmlReader();
SAXParserFactory spf = SAXParserFactory.newInstance();
try {
SAXParser sp = spf.newSAXParser();
InputStream is = mContext.getAssets().open(filePath);
sp.parse(is, myXMLHandler);
list.addAll(myXMLHandler.getBeerStyles());
} catch (Exception e) {
Log.e("getStylesFromXml", e.toString());
}
return list;
}
@Test
public void test() throws Exception {
SAXParserFactory fac = SAXParserFactory.newInstance();
fac.setNamespaceAware(true);
SAXParser saxParser = fac.newSAXParser();
StreamSource sr = new StreamSource(this.getClass().getResourceAsStream("SAX2DOMTest.xml"));
InputSource is = SAXSource.sourceToInputSource(sr);
RejectDoctypeSaxFilter rf = new RejectDoctypeSaxFilter(saxParser);
SAXSource src = new SAXSource(rf, is);
Transformer transformer = TransformerFactory.newInstance().newTransformer();
DOMResult result = new DOMResult();
transformer.transform(src, result);
Document doc = (Document) result.getNode();
System.out.println("Name" + doc.getDocumentElement().getLocalName());
String id = "XWSSGID-11605791027261938254268";
Element selement = doc.getElementById(id);
if (selement == null) {
System.out.println("getElementById returned null");
}
}
public void parseDocument(URL oscarURL) {
//get a factory
SAXParserFactory spf = SAXParserFactory.newInstance();
try {
//get a new instance of parser
SAXParser sp = spf.newSAXParser();
//parse the file and also register this class for call backs
InputStream is = new BufferedInputStream(oscarURL.openStream());
sp.parse(is, this);
System.out.println("done parsing count="+count);
is.close();
} catch (SAXException se) {
se.printStackTrace();
} catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (IOException ie) {
ie.printStackTrace();
}
}
public static cfData wddx2Cfml( String _wddxString, cfSession _Session ) throws cfmRunTimeException{
wddxHandler handler = new wddxHandler( _Session );//TODO: remove, _output );
SAXParserFactory factory = SAXParserFactory.newInstance();
try{
SAXParser xmlParser = factory.newSAXParser();
InputSource ip = new InputSource( new StringReader( _wddxString ));
xmlParser.parse( ip, handler );
return handler.getResult();
}catch(Exception e){
cfCatchData catchData = new cfCatchData( _Session );
catchData.setType( "WDDX" );
catchData.setDetail( "CFWDDX" );
catchData.setMessage( "Error deserializing WDDX string: " + (e instanceof NullPointerException ? "Badly Formatted xml" : e.getMessage() ) );
throw new cfmRunTimeException( catchData );
}
}
/**
* Parse the given XML string an create/update the corresponding entities
*
* @param xml
* the XML string
* @return the parse return code
* @throws Exception
*/
public int parse(byte[] xml) throws Exception {
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setNamespaceAware(true);
SchemaFactory sf = SchemaFactory
.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
try (InputStream inputStream = ResourceLoader.getResourceAsStream(
getClass(), getSchemaName())) {
Schema schema = sf.newSchema(new StreamSource(inputStream));
spf.setSchema(schema);
}
SAXParser saxParser = spf.newSAXParser();
XMLReader reader = saxParser.getXMLReader();
reader.setFeature(Constants.XERCES_FEATURE_PREFIX
+ Constants.DISALLOW_DOCTYPE_DECL_FEATURE, true);
reader.setContentHandler(this);
reader.parse(new InputSource(new ByteArrayInputStream(xml)));
return 0;
}
public void parse(InputStream xml, OutputStream finf, String workingDirectory) throws Exception {
StAXDocumentSerializer documentSerializer = new StAXDocumentSerializer();
documentSerializer.setOutputStream(finf);
SAX2StAXWriter saxTostax = new SAX2StAXWriter(documentSerializer);
SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
saxParserFactory.setNamespaceAware(true);
SAXParser saxParser = saxParserFactory.newSAXParser();
XMLReader reader = saxParser.getXMLReader();
reader.setProperty("http://xml.org/sax/properties/lexical-handler", saxTostax);
reader.setContentHandler(saxTostax);
if (workingDirectory != null) {
reader.setEntityResolver(createRelativePathResolver(workingDirectory));
}
reader.parse(new InputSource(xml));
xml.close();
finf.close();
}
@NonNull
public static RepoDetails getFromFile(InputStream inputStream, int pushRequests) {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(true);
SAXParser parser = factory.newSAXParser();
XMLReader reader = parser.getXMLReader();
RepoDetails repoDetails = new RepoDetails();
MockRepo mockRepo = new MockRepo(100, pushRequests);
RepoXMLHandler handler = new RepoXMLHandler(mockRepo, repoDetails);
reader.setContentHandler(handler);
InputSource is = new InputSource(new BufferedInputStream(inputStream));
reader.parse(is);
return repoDetails;
} catch (ParserConfigurationException | SAXException | IOException e) {
e.printStackTrace();
fail();
// Satisfies the compiler, but fail() will always throw a runtime exception so we never
// reach this return statement.
return null;
}
}
/**
* Parse and load the given filter file.
*
* @param fileName
* name of the filter file
* @throws IOException
* @throws SAXException
* @throws ParserConfigurationException
*/
private void parse(String fileName, @WillClose InputStream stream) throws IOException, SAXException, ParserConfigurationException {
try {
SAXBugCollectionHandler handler = new SAXBugCollectionHandler(this, new File(fileName));
SAXParserFactory parserFactory = SAXParserFactory.newInstance();
parserFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
parserFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", Boolean.TRUE);
parserFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", Boolean.FALSE);
parserFactory.setFeature("http://xml.org/sax/features/external-general-entities", Boolean.FALSE);
parserFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", Boolean.FALSE);
SAXParser parser = parserFactory.newSAXParser();
XMLReader xr = parser.getXMLReader();
xr.setContentHandler(handler);
xr.setErrorHandler(handler);
Reader reader = Util.getReader(stream);
xr.parse(new InputSource(reader));
} finally {
Util.closeSilently(stream);
}
}
public void parse( InputSource source, ContentHandler handler,
ErrorHandler errorHandler, EntityResolver entityResolver )
throws SAXException, IOException {
try {
SAXParser saxParser = allowFileAccess(factory.newSAXParser(), false);
XMLReader reader = new XMLReaderEx(saxParser.getXMLReader());
reader.setContentHandler(handler);
if(errorHandler!=null)
reader.setErrorHandler(errorHandler);
if(entityResolver!=null)
reader.setEntityResolver(entityResolver);
reader.parse(source);
} catch( ParserConfigurationException e ) {
// in practice this won't happen
SAXParseException spe = new SAXParseException(e.getMessage(),null,e);
errorHandler.fatalError(spe);
throw spe;
}
}
@NonNull
private Document parse(@NonNull String xml, @NonNull InputSource input, boolean checkBom)
throws ParserConfigurationException, SAXException, IOException {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setFeature(NAMESPACE_FEATURE, true);
factory.setFeature(NAMESPACE_PREFIX_FEATURE, true);
SAXParser parser = factory.newSAXParser();
DomBuilder handler = new DomBuilder(xml);
parser.parse(input, handler);
return handler.getDocument();
} catch (SAXException e) {
if (checkBom && e.getMessage().contains("Content is not allowed in prolog")) {
// Byte order mark in the string? Skip it. There are many markers
// (see http://en.wikipedia.org/wiki/Byte_order_mark) so here we'll
// just skip those up to the XML prolog beginning character, <
xml = xml.replaceFirst("^([\\W]+)<","<"); //$NON-NLS-1$ //$NON-NLS-2$
return parse(xml, new InputSource(new StringReader(xml)), false);
}
throw e;
}
}
/**
* Configure schema validation as recommended by the JAXP 1.2 spec.
* The <code>properties</code> object may contains information about
* the schema local and language.
* @param properties parser optional info
*/
private static void configureOldXerces(SAXParser parser,
Properties properties)
throws ParserConfigurationException,
SAXNotSupportedException {
String schemaLocation = (String)properties.get("schemaLocation");
String schemaLanguage = (String)properties.get("schemaLanguage");
try{
if (schemaLocation != null) {
parser.setProperty(JAXP_SCHEMA_LANGUAGE, schemaLanguage);
parser.setProperty(JAXP_SCHEMA_SOURCE, schemaLocation);
}
} catch (SAXNotRecognizedException e){
log.info(parser.getClass().getName() + ": "
+ e.getMessage() + " not supported.");
}
}
/**
* {@inheritDoc}
*/
public BodyParserResults parse(String xml) throws BOSHException {
BodyParserResults result = new BodyParserResults();
Exception thrown;
try {
InputStream inStream = new ByteArrayInputStream(xml.getBytes());
SAXParser parser = getSAXParser();
parser.parse(inStream, new Handler(parser, result));
return result;
} catch (SAXException saxx) {
thrown = saxx;
} catch (IOException iox) {
thrown = iox;
}
throw(new BOSHException("Could not parse body:\n" + xml, thrown));
}
public void parse( InputSource source, ContentHandler handler,
ErrorHandler errorHandler, EntityResolver entityResolver )
throws SAXException, IOException {
try {
SAXParser saxParser = allowFileAccess(factory.newSAXParser(), false);
XMLReader reader = new XMLReaderEx(saxParser.getXMLReader());
reader.setContentHandler(handler);
if(errorHandler!=null)
reader.setErrorHandler(errorHandler);
if(entityResolver!=null)
reader.setEntityResolver(entityResolver);
reader.parse(source);
} catch( ParserConfigurationException e ) {
// in practice this won't happen
SAXParseException spe = new SAXParseException(e.getMessage(),null,e);
errorHandler.fatalError(spe);
throw spe;
}
}
public void parseDocument(URL oscarURL) {
//get a factory
SAXParserFactory spf = SAXParserFactory.newInstance();
try {
//get a new instance of parser
SAXParser sp = spf.newSAXParser();
//parse the file and also register this class for call backs
InputStream is = new BufferedInputStream(oscarURL.openStream());
sp.parse(is, this);
System.out.println("done parsing count="+count);
is.close();
} catch (SAXException se) {
se.printStackTrace();
} catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (IOException ie) {
ie.printStackTrace();
}
}
/**
* Reads a {@link PieDataset} from a stream.
*
* @param in the input stream.
*
* @return A dataset.
*
* @throws IOException if there is an I/O error.
*/
public static PieDataset readPieDatasetFromXML(InputStream in)
throws IOException {
PieDataset result = null;
SAXParserFactory factory = SAXParserFactory.newInstance();
try {
SAXParser parser = factory.newSAXParser();
PieDatasetHandler handler = new PieDatasetHandler();
parser.parse(in, handler);
result = handler.getDataset();
}
catch (SAXException e) {
System.out.println(e.getMessage());
}
catch (ParserConfigurationException e2) {
System.out.println(e2.getMessage());
}
return result;
}
public ArrayList<Episode> fetchEpisodes(String feedUrl, Podcast podcast) {
try {
Request request = new Request.Builder().url(feedUrl).build();
String response = BackendManager.getInstance().sendSimpleSynchronicRequest(request);
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
EpisodesXMLHandler episodesXMLHandler = new EpisodesXMLHandler();
xr.setContentHandler(episodesXMLHandler);
//TODO could be encoding problem
InputSource inputSource = new InputSource(new StringReader(response));
xr.parse(inputSource);
ArrayList<Episode> parsedEpisodes = episodesXMLHandler.getParsedEpisods();
if (podcast != null) {
podcast.setDescription(episodesXMLHandler.getPodcastSummary());
}
return parsedEpisodes;
} catch (Exception e) {
Logger.printError(TAG, "Can't fetch episodes for url: " + feedUrl);
e.printStackTrace();
return new ArrayList<Episode>();
}
}
/** Obtain data logged by a scan
* @param id ID that uniquely identifies a scan (within JVM of the scan engine)
* @return {@link ScanData}
* @throws Exception on error
*/
public ScanData getScanData(final long id) throws Exception
{
final HttpURLConnection connection = connect("/scan/" + id + "/data");
try
{
checkResponse(connection);
final InputStream stream = connection.getInputStream();
final ScanDataSAXHandler handler = new ScanDataSAXHandler();
final SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
parser.parse(stream, handler);
return handler.getScanData();
}
finally
{
connection.disconnect();
}
}
@Test
public void test() throws SAXException, ParserConfigurationException, IOException {
Schema schema = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema").newSchema(new StreamSource(new StringReader(xmlSchema)));
SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
saxParserFactory.setNamespaceAware(true);
saxParserFactory.setSchema(schema);
// saxParserFactory.setFeature("http://java.sun.com/xml/schema/features/report-ignored-element-content-whitespace",
// true);
SAXParser saxParser = saxParserFactory.newSAXParser();
XMLReader xmlReader = saxParser.getXMLReader();
xmlReader.setContentHandler(new MyContentHandler());
// InputStream input =
// ClassLoader.getSystemClassLoader().getResourceAsStream("test/test.xml");
InputStream input = getClass().getResourceAsStream("Bug6946312.xml");
System.out.println("Parse InputStream:");
xmlReader.parse(new InputSource(input));
if (!charEvent) {
Assert.fail("missing character event");
}
}
public void parseFile(String filePath) {
String myerror = "";
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setValidating(false);
SAXParser parser = factory.newSAXParser();
InputSource inp = new InputSource (new FileReader(filePath));
parser.parse(inp, this);
} catch (SAXParseException err) {
myerror = "\n** Parsing error" + ", line " + err.getLineNumber()
+ ", uri " + err.getSystemId();
myerror += "\n" + err.getMessage();
System.out.println("myerror = " + myerror);
} catch (SAXException e) {
Exception x = e;
if (e.getException() != null)
x = e.getException();
myerror += "\nSAXException --" + x.getMessage();
System.out.println("myerror = " + myerror);
} catch (Exception eee) {
eee.printStackTrace();
myerror += "\nException --" + eee.getMessage();
System.out.println("myerror = " + myerror);
}
}
public Feed parseFeed(Feed feed) throws SAXException, IOException,
ParserConfigurationException, UnsupportedFeedtypeException {
TypeGetter tg = new TypeGetter();
TypeGetter.Type type = tg.getType(feed);
SyndHandler handler = new SyndHandler(feed, type);
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(true);
SAXParser saxParser = factory.newSAXParser();
File file = new File(feed.getFile_url());
Reader inputStreamReader = new XmlStreamReader(file);
InputSource inputSource = new InputSource(inputStreamReader);
saxParser.parse(inputSource, handler);
inputStreamReader.close();
return handler.state.feed;
}
@Override
protected void initBundle(InputStream is, File filename) throws IOException {
super.initBundle(is, filename);
keySet.clear();
this.is.reset();
ZipInputStream zip = new ZipInputStream(this.is);
ZipEntry entry;
while ((entry = zip.getNextEntry()) != null) {
if (entry.getName().equals("catalog.xml")) {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
DefaultHandler handler = new DefaultHandler() {
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if (qName.equalsIgnoreCase("library")) {
String path = attributes.getValue("path");
if (path != null) {
keySet.add(path);
}
}
}
};
saxParser.parse(zip, handler);
} catch (Exception ex) {
}
return;
}
}
}
public POXMembershipsResponse(Reader reader) {
try {
SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
parser.parse(new InputSource(reader), handler);
reader.close();
} catch (Exception e) {
log.error("Failed to parse memberships xml.", e);
}
}
@Override
public void processMapRef(HelpSet hs, @SuppressWarnings("rawtypes") Hashtable attrs) {
try {
URL map = new URL(hs.getHelpSetURL(), (String)attrs.get("location"));
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setValidating(false);
factory.setNamespaceAware(false);
SAXParser parser = factory.newSAXParser();
parser.parse(new InputSource(map.toExternalForm()), new Handler(map.getFile()));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Creates a new instance of <code>SAXParser</code> using the currently
* configured factory parameters.
* @return javax.xml.parsers.SAXParser
*/
public SAXParser newSAXParser()
throws ParserConfigurationException
{
SAXParser saxParserImpl;
try {
saxParserImpl = new SAXParserImpl(this, features, fSecureProcess);
} catch (SAXException se) {
// Translate to ParserConfigurationException
throw new ParserConfigurationException(se.getMessage());
}
return saxParserImpl;
}
public static void main(String[] args) {
SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
try {
SAXParser saxParser = saxParserFactory.newSAXParser();
MyHandler handler = new MyHandler();
saxParser.parse(new File("employees.xml"), handler);
// Get Employees list
List<Employee> empList = handler.getEmpList();
// print employee information
for (Employee emp : empList)
System.out.println(emp);
} catch (ParserConfigurationException | SAXException | IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args)
throws ParserConfigurationException, SAXException, IOException {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
SAXHandel handel = new SAXHandel();
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(Payloads.FEEDBACK.getBytes());
saxParser.parse(byteArrayInputStream, handel);
}
public static QuickServerXmlParser parse(final String serverXmlContents) {
final QuickServerXmlParser handler = new QuickServerXmlParser();
try {
final SAXParser parser = FACTORY.newSAXParser();
parser.parse(new ByteArrayInputStream(serverXmlContents.getBytes()), handler);
} catch (final Exception e) {
// no-op: using defaults
}
return handler;
}