private SVNErrorMessage readData( InputStream is, String method, String path, DefaultHandler handler) throws FactoryConfigurationError, UnsupportedEncodingException, IOException { try { if (mySAXParser == null) { mySAXParser = getSAXParserFactory().newSAXParser(); } XMLReader reader = new XMLReader(is); while (!reader.isClosed()) { org.xml.sax.XMLReader xmlReader = mySAXParser.getXMLReader(); xmlReader.setContentHandler(handler); xmlReader.setDTDHandler(handler); xmlReader.setErrorHandler(handler); xmlReader.setEntityResolver(NO_ENTITY_RESOLVER); xmlReader.parse(new InputSource(reader)); } } catch (SAXException e) { if (e instanceof SAXParseException) { if (handler instanceof DAVErrorHandler) { // failed to read svn-specific error, return null. return null; } } else if (e.getException() instanceof SVNException) { return ((SVNException) e.getException()).getErrorMessage(); } else if (e.getCause() instanceof SVNException) { return ((SVNException) e.getCause()).getErrorMessage(); } return SVNErrorMessage.create( SVNErrorCode.RA_DAV_REQUEST_FAILED, "Processing {0} request response failed: {1} ({2}) ", new Object[] {method, e.getMessage(), path}); } catch (ParserConfigurationException e) { return SVNErrorMessage.create( SVNErrorCode.RA_DAV_REQUEST_FAILED, "XML parser configuration error while processing {0} request response: {1} ({2}) ", new Object[] {method, e.getMessage(), path}); } catch (EOFException e) { // skip it. } finally { if (mySAXParser != null) { // to avoid memory leaks when connection is cached. org.xml.sax.XMLReader xmlReader = null; try { xmlReader = mySAXParser.getXMLReader(); } catch (SAXException e) { } if (xmlReader != null) { xmlReader.setContentHandler(DEFAULT_SAX_HANDLER); xmlReader.setDTDHandler(DEFAULT_SAX_HANDLER); xmlReader.setErrorHandler(DEFAULT_SAX_HANDLER); xmlReader.setEntityResolver(NO_ENTITY_RESOLVER); } } myRepository.getDebugLog().flushStream(is); } return null; }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.flash_card_activity); // Initialize fields initialize(); try { SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); myParser = new XMLParser(); xr.setContentHandler(myParser); xr.parse(new InputSource(this.getResources().openRawResource(R.raw.words))); } catch (Exception e) { e.printStackTrace(); } finally { words = myParser.getWordsList(); // db = dbh.getWritableDatabase(); // myWords = dbh.getMyWordsList(); displayWord(words.get(index)); } pbProgress.setMax(words.size()); }
public void loadIdea() { try { URL url = new URL(idea_url); SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); IdeaDetailHandler myExampleHandler = new IdeaDetailHandler(); xr.setContentHandler(myExampleHandler); InputSource is = new InputSource(url.openStream()); is.setEncoding("UTF-8"); xr.parse(is); idea = myExampleHandler.getParsedData(); Message myMessage = new Message(); myMessage.obj = "SUCCESS"; handler.sendMessage(myMessage); } catch (Exception e) { // Log.e("Ideas4All", "Error", e); } }
/** * Deconstructs response into given content handler * * @param entity returned HttpEntity * @return deconstructed response * @throws java.io.IOException * @see org.apache.http.HttpEntity */ @Override protected byte[] getResponseData(HttpEntity entity) throws IOException { if (entity != null) { InputStream instream = entity.getContent(); InputStreamReader inputStreamReader = null; if (instream != null) { try { SAXParserFactory sfactory = SAXParserFactory.newInstance(); SAXParser sparser = sfactory.newSAXParser(); XMLReader rssReader = sparser.getXMLReader(); rssReader.setContentHandler(handler); inputStreamReader = new InputStreamReader(instream, DEFAULT_CHARSET); rssReader.parse(new InputSource(inputStreamReader)); } catch (SAXException e) { Log.e(LOG_TAG, "getResponseData exception", e); } catch (ParserConfigurationException e) { Log.e(LOG_TAG, "getResponseData exception", e); } finally { AsyncHttpClient.silentCloseInputStream(instream); if (inputStreamReader != null) { try { inputStreamReader.close(); } catch (IOException e) { /*ignore*/ } } } } } return null; }
private boolean loadParticleXML() { InputStream is = null; try { SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); QuickTiGame2dParticleParser handler = new QuickTiGame2dParticleParser(this); XMLReader xr = sp.getXMLReader(); xr.setContentHandler(handler); is = QuickTiGame2dUtil.getFileInputStream(image); xr.parse(new InputSource(new BufferedInputStream(is))); emissionRate = maxParticles / particleLifespan; sourcePosition.x = x; sourcePosition.y = y; } catch (Exception e) { if (debug) Log.w(Quicktigame2dModule.LOG_TAG, String.format("failed to load particle: %s", image), e); return false; } finally { if (is != null) { try { is.close(); } catch (IOException e) { // nothing to do } } } return true; }
private static Service parseServicePayload(String payload) throws ResponseParseException { JAXBContext jaxbContext; Service service = null; try { jaxbContext = JAXBContext.newInstance(Service.class); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); InputStream inputStream = new ByteArrayInputStream(payload.getBytes(Charset.forName("UTF-8"))); SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); SAXParser sp = spf.newSAXParser(); XMLReader xmlReader = sp.getXMLReader(); InputSource inputSource = new InputSource(inputStream); SAXSource saxSource = new SAXSource(xmlReader, inputSource); service = (Service) jaxbUnmarshaller.unmarshal(saxSource); } catch (JAXBException | FactoryConfigurationError | ParserConfigurationException | SAXException e) { throw new ResponseParseException(e); } return service; }
public void load(PageProcessor processor) { SAXParserFactory factory = SAXParserFactory.newInstance(); try { SAXParser parser = factory.newSAXParser(); XMLReader xmlReader = parser.getXMLReader(); // String file = "enwiki-20151201-pages-meta-current.xml.bz2"; xmlReader.setContentHandler(new PageHandler(xmlReader)); FileInputStream fis = new FileInputStream(fileName); BZip2CompressorInputStream bzIn = new BZip2CompressorInputStream(fis); InputSource inputSource = new InputSource(bzIn); xmlReader.parse(inputSource); System.out.println("###### " + threadName + " processing completed ######"); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { // System.out.println("Closing Thread- " + threadName); DataIndexer.getInstance().threadClosing(); } }
/** * This method parses the data from the BBC XML link, via the SAX Parser and XMLHandler class. * * @see XMLHandler */ private void getNews() { try { URL xmlUrl = new URL("http://feeds.bbci.co.uk/news/uk/rss.xml"); SAXParserFactory mySAXParserFactory = SAXParserFactory.newInstance(); SAXParser mySAXParser = mySAXParserFactory.newSAXParser(); XMLReader myXMLReader = mySAXParser.getXMLReader(); XMLHandler myXMLHandler = new XMLHandler(); myXMLReader.setContentHandler(myXMLHandler); InputSource myInputSource = new InputSource(xmlUrl.openStream()); myXMLReader.parse(myInputSource); myXMLFeed = myXMLHandler.getFeed(); } // catch a bunch of exceptions catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ParserConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
public ArrayList<String> recomendaciones() { try { String direccion = "http://www.thetvdb.com/api/User_Favorites.php?accountid=7FB13C3CF230D455"; URL url = new URL(direccion); HttpURLConnection conexion = (HttpURLConnection) url.openConnection(); if (conexion.getResponseCode() == HttpURLConnection.HTTP_OK) { SAXParserFactory fabrica = SAXParserFactory.newInstance(); SAXParser parser = fabrica.newSAXParser(); XMLReader lector = parser.getXMLReader(); ManejadorSerWeb manejadorXML = new ManejadorSerWeb(); lector.setContentHandler(manejadorXML); lector.parse(new InputSource(conexion.getInputStream())); return manejadorXML.getRecomendaciones(); } else { Log.e("ANDseries", conexion.getResponseMessage()); return null; } } catch (Exception e) { Log.e("ANDseries", e.getMessage(), e); return null; } }
public WebXMLDefinition loadWebXML() throws Exception { URL url = _bundle.getEntry("WEB-INF/web.xml"); if (url != null) { try (InputStream inputStream = url.openStream()) { SAXParser saxParser = _saxParserFactory.newSAXParser(); XMLReader xmlReader = saxParser.getXMLReader(); xmlReader.setContentHandler(this); xmlReader.parse(new InputSource(inputStream)); } catch (SAXParseException saxpe) { String message = saxpe.getMessage(); if (message.contains("DOCTYPE is disallowed")) { throw new Exception( "WEB-INF/web.xml must be updated to the Servlet 2.4 " + "specification"); } throw saxpe; } } return _webXMLDefinition; }
private XMLReader getXMLReader(ContentHandler contentHandler, ErrorHandler errorHandler) throws ParserConfigurationException, SAXException { // setup sax factory ; be sure just one instance! SAXParserFactory saxFactory = SAXParserFactory.newInstance(); // Enable validation stuff saxFactory.setValidating(true); saxFactory.setNamespaceAware(true); // Create xml reader SAXParser saxParser = saxFactory.newSAXParser(); XMLReader xmlReader = saxParser.getXMLReader(); // Setup xmlreader xmlReader.setProperty( XMLReaderObjectFactory.APACHE_PROPERTIES_INTERNAL_GRAMMARPOOL, grammarPool); xmlReader.setFeature(Namespaces.SAX_VALIDATION, true); xmlReader.setFeature(Namespaces.SAX_VALIDATION_DYNAMIC, false); xmlReader.setFeature(XMLReaderObjectFactory.APACHE_FEATURES_VALIDATION_SCHEMA, true); xmlReader.setFeature(XMLReaderObjectFactory.APACHE_PROPERTIES_LOAD_EXT_DTD, true); xmlReader.setFeature(Namespaces.SAX_NAMESPACES_PREFIXES, true); xmlReader.setContentHandler(contentHandler); xmlReader.setErrorHandler(errorHandler); return xmlReader; }
public RSSFeed readFile() { try { // get the XML reader SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser parser = factory.newSAXParser(); XMLReader xmlreader = parser.getXMLReader(); // set content handler RSSFeedHandler theRssHandler = new RSSFeedHandler(); xmlreader.setContentHandler(theRssHandler); // read the file from internal storage FileInputStream in = context.openFileInput(FILENAME); // parse the data InputSource is = new InputSource(in); xmlreader.parse(is); // set the feed in the activity RSSFeed feed = theRssHandler.getFeed(); return feed; } catch (Exception e) { Log.e("News reader", e.toString()); return null; } }
public void parseServicesXml(String servicesDotXml) { try { /* Create a URL we want to load some xml-data from. */ // URL url = new URL("https://services.appmobi.com/testing/AppConfig.xml"); /* Get a SAXParser from the SAXPArserFactory. */ SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); /* Get the XMLReader of the SAXParser we created. */ XMLReader xr = sp.getXMLReader(); /* Create a new ContentHandler and apply it to the XML-Reader*/ ServicesHandler handler = new ServicesHandler(this); xr.setContentHandler(handler); /* Parse the xml-data from our URL. */ xr.parse(new InputSource(new StringReader(servicesDotXml))); /* Parsing has finished. */ } catch (Exception e) { /* Display any Error to the GUI. */ // if(Debug.isDebuggerConnected()) Log.e("[appMobi]", "services.xml Parsing Error", e); } }
@Override public void internalParse(InputStream input) { try { try { Thread.sleep(4000); } catch (Throwable t) { } SAXParserFactory saxParserFactory = SAXParserFactory.newInstance(); saxParserFactory.setValidating(false); SAXParser saxParser = saxParserFactory.newSAXParser(); XMLReader xmlReader = saxParser.getXMLReader(); xmlReader.setFeature("http://xml.org/sax/features/validation", false); xmlReader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); ZipInputStream zis = new ZipInputStream(input); ZipEntry ze = zis.getNextEntry(); while (ze != null && !ze.getName().equals("content.xml")) { ze = zis.getNextEntry(); } OpenOfficeContentHandler contentHandler = new OpenOfficeContentHandler(); xmlReader.setContentHandler(contentHandler); try { xmlReader.parse(new InputSource(zis)); } finally { zis.close(); } content.append(StringUtil.writeToString(new StringReader(contentHandler.getContent()))); } catch (Exception e) { log.warn("Failed to extract OpenOffice text content", e); } }
public void testWithDummyExtSubset() throws Exception { final String XML = "<!DOCTYPE root PUBLIC '//some//public//id' 'no-such-thing.dtd'>\n" + "<root />"; SAXParserFactoryImpl spf = new SAXParserFactoryImpl(); spf.setNamespaceAware(true); SAXParser sp = spf.newSAXParser(); DefaultHandler h = new DefaultHandler(); /* First: let's verify that we get an exception for * unresolved reference... */ try { sp.parse(new InputSource(new StringReader(XML)), h); } catch (SAXException e) { verifyException(e, "No such file or directory"); } // And then with dummy resolver; should work ok now sp = spf.newSAXParser(); sp.getXMLReader().setEntityResolver(new MyResolver(" ")); h = new DefaultHandler(); try { sp.parse(new InputSource(new StringReader(XML)), h); } catch (SAXException e) { fail( "Should not have failed with entity resolver, got (" + e.getClass() + "): " + e.getMessage()); } }
Parser(String uri) { try { SAXParserFactory parserFactory = SAXParserFactory.newInstance(); SAXParser parser = parserFactory.newSAXParser(); ConfigHandler handler = new ConfigHandler(); parser.getXMLReader().setFeature("http://xml.org/sax/features/validation", true); parser.parse(new File(uri), handler); } catch (IOException e) { System.out.println("Error reading URI: " + e.getMessage()); } catch (SAXException e) { System.out.println("Error in parsing: " + e.getMessage()); } catch (ParserConfigurationException e) { System.out.println("Error in XML parser configuration: " + e.getMessage()); } // System.out.println("Number of Persons : " + Person.numberOfPersons()); // nameLengthStatistics(); // System.out.println("Number of Publications with authors/editors: " + // Publication.getNumberOfPublications()); // System.out.println("Maximum number of authors/editors in a publication: " + // Publication.getMaxNumberOfAuthors()); // publicationCountStatistics(); // Person.enterPublications(); // Person.printCoauthorTable(); // Person.printNamePartTable(); // Person.findSimilarNames(); }
@Override protected String getDocumentText(String absolutePath, String encoding) throws IOException { String text; try { SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setValidating(false); spf.setNamespaceAware(true); spf.setFeature("http://xml.org/sax/features/namespaces", true); spf.setFeature("http://xml.org/sax/features/validation", false); spf.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false); spf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); SAXParser saxParser = spf.newSAXParser(); XMLReader xmlReader = saxParser.getXMLReader(); TeiToTxtSaxHandler handler = new TeiToTxtSaxHandler(); xmlReader.setContentHandler(handler); xmlReader.parse(new InputSource(absolutePath)); text = handler.getText(); } catch (ParserConfigurationException | SAXException e) { logger.error("Could not read TEI document: {}", absolutePath); logger.warn("Ignoring TEI document " + absolutePath); text = ""; this.failedFileCounter++; } return text; }
private static SVG parse( InputStream in, Integer searchColor, Integer replaceColor, boolean whiteMode) throws SVGParseException { // Util.debug("Parsing SVG..."); try { // long start = System.currentTimeMillis(); SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); final Picture picture = new Picture(); SVGHandler handler = new SVGHandler(picture); handler.setColorSwap(searchColor, replaceColor); handler.setWhiteMode(whiteMode); xr.setContentHandler(handler); xr.parse(new InputSource(in)); // Util.debug("Parsing complete in " + (System.currentTimeMillis() - start) + " // millis."); SVG result = new SVG(picture, handler.bounds); // Skip bounds if it was an empty pic if (!Float.isInfinite(handler.limits.top)) { result.setLimits(handler.limits); } return result; } catch (Exception e) { throw new SVGParseException(e); } }
private CloudServersException parseCloudServersException(HttpResponse response) { CloudServersException cse = new CloudServersException(); try { BasicResponseHandler responseHandler = new BasicResponseHandler(); String body = responseHandler.handleResponse(response); CloudServersFaultXMLParser parser = new CloudServersFaultXMLParser(); SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser(); XMLReader xmlReader = saxParser.getXMLReader(); xmlReader.setContentHandler(parser); xmlReader.parse(new InputSource(new StringReader(body))); cse = parser.getException(); } catch (ClientProtocolException e) { cse = new CloudServersException(); cse.setMessage(e.getLocalizedMessage()); } catch (IOException e) { cse = new CloudServersException(); cse.setMessage(e.getLocalizedMessage()); } catch (ParserConfigurationException e) { cse = new CloudServersException(); cse.setMessage(e.getLocalizedMessage()); } catch (SAXException e) { cse = new CloudServersException(); cse.setMessage(e.getLocalizedMessage()); } catch (FactoryConfigurationError e) { cse = new CloudServersException(); cse.setMessage(e.getLocalizedMessage()); } return cse; }
// This method is executed in the background thread on our Survey object private String uploadSurveyData(String myXML) { // Set up communication with the server DefaultHttpClient client = new DefaultHttpClient(); String result = null; // HttpPost httpPost; httpPost = new HttpPost( "http://YOUR DOMAIN HERE/survey-webApp/index.php/webUser_Controllers/android_controller/save_survey_xml"); try { // Encode the xml, add header and set it to POST request StringEntity entity = new StringEntity(myXML, HTTP.UTF_8); // entity.setContentType("text/xml"); httpPost.setEntity(entity); // Execute POST request and get response HttpResponse response = client.execute(httpPost); HttpEntity responseEntity = response.getEntity(); // System.out.print(EntityUtils.toString(responseEntity)); // Set up XML parsing objects SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); // Set up an instance of our class to parse the status response HttpResponseHandler myResponseHandler = new HttpResponseHandler(); xr.setContentHandler(myResponseHandler); xr.parse(retrieveInputStream(responseEntity)); // check myResponseHandler for response result = myResponseHandler.getStatus(); } catch (Exception e) { result = "Exception - " + e.getMessage(); } return result; }
private void processCommentLines(File file) throws SAXException, IOException { SAXParser parser = newSaxParser(false); XMLReader xmlReader = parser.getXMLReader(); commentHandler = new CommentHandler(); xmlReader.setProperty("http://xml.org/sax/properties/lexical-handler", commentHandler); parser.parse(FileUtils.openInputStream(file), commentHandler); }
private void fetchComments() { try { final URL newUrl = new URL(book.get().getCommentsUrl()); // sax stuff final SAXParserFactory factory = SAXParserFactory.newInstance(); final SAXParser parser = factory.newSAXParser(); final XMLReader reader = parser.getXMLReader(); // initialize our parser logic final CommentsHandler commentsHandler = new CommentsHandler(book.get().getComments()); reader.setContentHandler(commentsHandler); // get the xml feed reader.parse(new InputSource(newUrl.openStream())); } catch (MalformedURLException e) { COMMENTS_ERROR = MALFORMED_URL; Log.e(TAG, "MalformedURLException: " + e + "\nIn fetchComments()"); } catch (ParserConfigurationException pce) { COMMENTS_ERROR = PARSER_CONFIG_ERROR; Log.e(TAG, "ParserConfigurationException: " + pce + "\nIn fetchComments()"); } catch (SAXException se) { COMMENTS_ERROR = SAX_ERROR; Log.e(TAG, "SAXException: " + se + "\nIn fetchComments()"); } catch (IOException ioe) { COMMENTS_ERROR = IO_ERROR; Log.e(TAG, "IOException: " + ioe + "\nIn fetchComments()"); } }
private RSSFeed getFeed(String urlToRssFeed) { try { // setup the url URL url = new URL(urlToRssFeed); // create the factory SAXParserFactory factory = SAXParserFactory.newInstance(); // create a parser SAXParser parser = factory.newSAXParser(); // create the reader (scanner) XMLReader xmlreader = parser.getXMLReader(); // instantiate our handler RSSHandler theRssHandler = new RSSHandler(); // assign our handler xmlreader.setContentHandler(theRssHandler); // get our data via the url class InputSource is = new InputSource(url.openStream()); // perform the synchronous parse xmlreader.parse(is); // get the results - should be a fully populated RSSFeed instance, // or null on error return theRssHandler.getFeed(); } catch (Exception ee) { // if we have a problem, simply return null return null; } }
@Override protected RssItem doInBackground(RssParser... params) { RssParser parser = params[0]; RssItem item = null; try { SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); xr.setContentHandler(parser); // chamar arquivo xml // xr.parse(new InputSource(activity.getAssets().open("image_of_the_day.xml"))); // chamar link na internet URL url = new URL("http://www.nasa.gov/rss/dyn/image_of_the_day.rss"); xr.parse(new InputSource(url.openConnection().getInputStream())); item = parser.getFirstItem(); if (item != null) { /*item.setImagem( BitmapFactory.decodeResource( activity.getResources(), R.drawable.image_of_the_day));*/ item.setImagem(getBitmap(item.getImagemUrl())); } } catch (Exception e) { e.printStackTrace(); } return item; }
/** Simple ctor */ public StringSAXEventProvider(String xmlstr) throws ParserConfigurationException, SAXException { this.xmlstr = xmlstr; SAXParserFactory fact = SAXParserFactory.newInstance(); SAXParser parser = fact.newSAXParser(); reader = parser.getXMLReader(); }
/** * 通过XSD(XML Schema)校验XML * * @throws FileNotFoundException */ public boolean validateXMLByXSD(String testXSD, String xmlFileName) throws FileNotFoundException { // String xmlFileName = "Q:\\_dev_stu\\xsdtest\\src\\note.xml"; String xsdFileName = "E:/datashare/" + testXSD; FileInputStream fls = new FileInputStream(new File(xmlFileName)); try { // 创建默认的XML错误处理器 XMLErrorHandler errorHandler = new XMLErrorHandler(); // 获取基于 SAX 的解析器的实例 SAXParserFactory factory = SAXParserFactory.newInstance(); // 解析器在解析时验证 XML 内容。 factory.setValidating(true); // 指定由此代码生成的解析器将提供对 XML 名称空间的支持。 factory.setNamespaceAware(true); // 使用当前配置的工厂参数创建 SAXParser 的一个新实例。 SAXParser parser = factory.newSAXParser(); // 创建一个读取工具 SAXReader xmlReader = new SAXReader(); // 获取要校验xml文档实例 Document xmlDocument = (Document) xmlReader.read(fls); // 设置 XMLReader 的基础实现中的特定属性。核心功能和属性列表可以在 // [url]http://sax.sourceforge.net/?selected=get-set[/url] 中找到。 parser.setProperty( "http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema"); parser.setProperty( "http://java.sun.com/xml/jaxp/properties/schemaSource", "file:" + xsdFileName); // 创建一个SAXValidator校验工具,并设置校验工具的属性 SAXValidator validator = new SAXValidator(parser.getXMLReader()); // 设置校验工具的错误处理器,当发生错误时,可以从处理器对象中得到错误信息。 validator.setErrorHandler(errorHandler); // 校验 validator.validate(xmlDocument); XMLWriter writer = new XMLWriter(OutputFormat.createPrettyPrint()); // 如果错误信息不为空,说明校验失败,打印错误信息 if (errorHandler.getErrors().hasContent()) { System.out.println("XML文件校验失败!"); writer.write(errorHandler.getErrors()); return false; } else { System.out.println("XML文件校验成功!"); return true; } } catch (Exception ex) { System.out.println( "XML文件: " + xmlFileName + " 通过XSD文件:" + xsdFileName + "检验失败。\n原因: " + ex.getMessage()); // ex.printStackTrace(); return false; } finally { try { fls.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
/** * Read this shared strings table from an XML file. * * @param is The input stream containing the XML document. * @throws IOException if an error occurs while reading. * @throws SAXException * @throws ParserConfigurationException */ public void readFrom(InputStream is) throws IOException, SAXException, ParserConfigurationException { InputSource sheetSource = new InputSource(is); SAXParserFactory saxFactory = SAXParserFactory.newInstance(); SAXParser saxParser = saxFactory.newSAXParser(); XMLReader sheetParser = saxParser.getXMLReader(); sheetParser.setContentHandler(this); sheetParser.parse(sheetSource); }
/** * Validates given XML file using specified schema. * * @param fileUrl the URL of the file to be validated. * @param schemaUrl the URL of the schema to be used. * @throws ParserConfigurationException if parser is badly configured. * @throws IOException if the schema does not exist. * @throws SAXException if the schema is malformed. */ public void validate(URL fileUrl, URL schemaUrl) throws SAXException, ParserConfigurationException, IOException { Verifier verifier = getVerifier(schemaUrl); XMLReader reader = saxParser.getXMLReader(); InputSource source = new InputSource(fileUrl.toString()); reader.setContentHandler(verifier); reader.setDTDHandler(verifier); reader.parse(source); }
/* * Main method to parse specific MetaData file. */ public Collection<Designate> doParse() throws IOException, SAXException { _dp_xmlReader = _dp_parser.getXMLReader(); _dp_xmlReader.setContentHandler(new RootHandler()); _dp_xmlReader.setErrorHandler(new MyErrorHandler(System.err)); InputStream is = _dp_url.openStream(); InputSource isource = new InputSource(is); logger.log(LogService.LOG_DEBUG, "Starting to parse " + _dp_url); // $NON-NLS-1$ _dp_xmlReader.parse(isource); return designates; }
public static XMLReader newXMLReader(XMLUtils.ParserConfiguration parserConfiguration) { final SAXParser saxParser = XMLUtils.newSAXParser(parserConfiguration); try { final XMLReader xmlReader = saxParser.getXMLReader(); xmlReader.setEntityResolver(XMLUtils.ENTITY_RESOLVER); xmlReader.setErrorHandler(XMLUtils.ERROR_HANDLER); return xmlReader; } catch (Exception e) { throw new OXFException(e); } }