/** * 用于防钓鱼,调用接口query_timestamp来获取时间戳的处理函数 * 注意:远程解析XML出错,与服务器是否支持SSL等配置有关 * @return 时间戳字符串 * @throws IOException * @throws DocumentException * @throws MalformedURLException */ public static String query_timestamp() throws MalformedURLException, DocumentException, IOException { //构造访问query_timestamp接口的URL串 String strUrl = ALIPAY_GATEWAY_NEW + "service=query_timestamp&partner=" + AlipayConfig.partner + "&_input_charset" +AlipayConfig.input_charset; StringBuffer result = new StringBuffer(); SAXReader reader = new SAXReader(); Document doc = reader.read(new URL(strUrl).openStream()); List<Node> nodeList = doc.selectNodes("//alipay/*"); for (Node node : nodeList) { // 截取部分不需要解析的信息 if (node.getName().equals("is_success") && node.getText().equals("T")) { // 判断是否有成功标示 List<Node> nodeList1 = doc.selectNodes("//response/timestamp/*"); for (Node node1 : nodeList1) { result.append(node1.getText()); } } } return result.toString(); }
public static DOM4JSettingsNode readSettingsFile(ImportInteraction importInteraction, FileFilter fileFilter) { File file = importInteraction.promptForFile(fileFilter); if (file == null) { return null; } if (!file.exists()) { importInteraction.reportError("File does not exist: " + file.getAbsolutePath()); return null; //we should really sit in a loop until they cancel or give us a valid file. } try { SAXReader reader = new SAXReader(); Document document = reader.read(file); return new DOM4JSettingsNode(document.getRootElement()); } catch (Throwable t) { LOGGER.error("Unable to read file: " + file.getAbsolutePath(), t); importInteraction.reportError("Unable to read file: " + file.getAbsolutePath()); return null; } }
public static Document parseText(String text) throws DocumentException, SAXException { SAXReader reader = new SAXReader(false); reader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); reader.setFeature("http://apache.org/xml/features/validation/schema", false); String encoding = getEncoding(text); InputSource source = new InputSource(new StringReader(text)); source.setEncoding(encoding); Document result = reader.read(source); // if the XML parser doesn't provide a way to retrieve the encoding, // specify it manually if (result.getXMLEncoding() == null) { result.setXMLEncoding(encoding); } return result; }
/** * 用于防钓鱼,调用接口query_timestamp来获取时间戳的处理函数 * 注意:远程解析XML出错,与服务器是否支持SSL等配置有关 * * @return 时间戳字符串 * @throws IOException * @throws DocumentException * @throws MalformedURLException */ public static String query_timestamp() throws MalformedURLException, DocumentException, IOException { //构造访问query_timestamp接口的URL串 String strUrl = PayManager.HTTPS_MAPI_ALIPAY_COM_GATEWAY_DO + "?" + "service=query_timestamp&partner=" + AlipayConfig.partner + "&_input_charset" + AlipayConfig.input_charset; StringBuffer result = new StringBuffer(); SAXReader reader = new SAXReader(); Document doc = reader.read(new URL(strUrl).openStream()); List<Node> nodeList = doc.selectNodes("//alipay/*"); for (Node node : nodeList) { // 截取部分不需要解析的信息 if (node.getName().equals("is_success") && node.getText().equals("T")) { // 判断是否有成功标示 List<Node> nodeList1 = doc.selectNodes("//response/timestamp/*"); for (Node node1 : nodeList1) { result.append(node1.getText()); } } } return result.toString(); }
public XMLBeanFactory(InputStream input) { SAXReader reader = new SAXReader(); Document doc = null; try { doc = reader.read(input); if (doc == null) return; } catch (DocumentException e) { e.printStackTrace(); } Element root = doc.getRootElement(); @SuppressWarnings("unchecked") List<Element> beanElems = root.elements(); for (Element beanElem : beanElems) { Bean bean = parseBeanElement(beanElem); addBean(bean); } instancetiateSingletons(); }
/** * 属性转化 * @param xmlFile xml文件 */ private void convert(File xmlFile){ SAXReader reader = new SAXReader(); try { Document document = reader.read(xmlFile); Element root = document.getRootElement(); root.element("id").setText(artifactId); root.element("name").setText(getJarPrefixName()); root.element("description").setText(null == description ? "暂无描述" : description); String javaArguments = ""; if (arguments != null) { for (String argument : arguments) { javaArguments = " " + argument; } } root.element("arguments").setText("-jar " + getJarName() + javaArguments); saveXML(document,xmlFile); } catch (Exception e) { e.printStackTrace(); } }
public String readXML(int xmlId, String textItem, int textId){ String xmlText; String xmlPath; Element xmlRoot,secRoot; URL xmlURL; Document xmlFile; SAXReader reader = new SAXReader(); xmlPath = "./data/language/" + language + "/" + rEadC.getConfig(rEadC.userConfig , "text", "xml" + xmlId); xmlURL = Resources.getResource(xmlPath); try { xmlFile = reader.read(xmlURL); xmlRoot = xmlFile.getRootElement(); secRoot = xmlRoot.element(textItem); xmlText = secRoot.elementText("adv" + textId); return xmlText; } catch (DocumentException e) { e.printStackTrace(); } return null; }
/** * 解析微信发来的请求(XML) * * @param request * @return Map<String, String> * @throws Exception */ @SuppressWarnings("unchecked") public static Map<String, String> parseXml(HttpServletRequest request) throws Exception { // 将解析结果存储在HashMap中 Map<String, String> map = new HashMap<String, String>(); // 从request中取得输入流 InputStream inputStream = request.getInputStream(); // 读取输入流 SAXReader reader = new SAXReader(); Document document = reader.read(inputStream); // 得到xml根元素 Element root = document.getRootElement(); // 得到根元素的所有子节点 List<Element> elementList = root.elements(); // 遍历所有子节点 for (Element e : elementList) map.put(e.getName(), e.getText()); // 释放资源 inputStream.close(); inputStream = null; return map; }
public void loadQueryCollection(String location) { try { InputStream is = this.getClass().getClassLoader().getResourceAsStream(location); SAXReader reader = new SAXReader(); Document document = reader.read(is); is.close(); QueryCollection collection = QueryCollectionImpl.createQueryCollection(document.getRootElement(), dictionaryService, namespaceService); collections.put(location, collection); } catch (DocumentException de) { throw new AlfrescoRuntimeException("Error reading XML", de); } catch (IOException e) { throw new AlfrescoRuntimeException("IO Error reading XML", e); } }
public static boolean hasRoot(File file, String name) { SAXReader reader = new SAXReader(); try(InputStream in = new FileInputStream(file)) { Document doc = reader.read(in); Element rootEle = doc.getRootElement(); String rootEleName = rootEle.getName(); return rootEleName.equals(name); } catch (Exception e) {} return false; }
/** * 用于防钓鱼,调用接口query_timestamp来获取时间戳的处理函数 * 注意:远程解析XML出错,与服务器是否支持SSL等配置有关 * @return 时间戳字符串 * @throws IOException * @throws DocumentException * @throws MalformedURLException */ public static String query_timestamp(AlipayConfig config) throws MalformedURLException, DocumentException, IOException { //构造访问query_timestamp接口的URL串 String strUrl = ALIPAY_GATEWAY_NEW + "service=query_timestamp&partner=" + config.getPartnerId() + "&_input_charset" +AlipayConfig.inputCharset; StringBuffer result = new StringBuffer(); SAXReader reader = new SAXReader(); Document doc = reader.read(new URL(strUrl).openStream()); List<Node> nodeList = doc.selectNodes("//alipay/*"); for (Node node : nodeList) { // 截取部分不需要解析的信息 if (node.getName().equals("is_success") && node.getText().equals("T")) { // 判断是否有成功标示 List<Node> nodeList1 = doc.selectNodes("//response/timestamp/*"); for (Node node1 : nodeList1) { result.append(node1.getText()); } } } return result.toString(); }
private Document getCollectionDocumentFromWebService ( String _key ) { Document collectionDocument = null; // make the call to DDS and get ListCollections try { URLConnection connection = new URL ("http://www.dlese.org/dds/services/ddsws1-1?verb=Search&ky=" + _key + "&n=200&s=0" ).openConnection(); connection.setDoOutput( true ); connection.setDoInput(true); ((HttpURLConnection)connection).setRequestMethod("GET"); SAXReader xmlReader = new SAXReader(); collectionDocument = xmlReader.read(connection.getInputStream()); } catch ( Exception e ) { e.printStackTrace(); } return collectionDocument; }
/** * Grabs the valid metadata formats from the DPC schema. * * @return A list of valid metadata formats. */ public ArrayList getValidMetadataFormats() { String metadataFormatSchemaUrl = getServlet().getServletContext().getInitParameter("metadataFormatSchemaUrl"); if (metadataFormatSchemaUrl == null) return null; if (validMetadataFormats == null) { try { validMetadataFormats = new ArrayList(); SAXReader reader = new SAXReader(); Document document = reader.read(new URL(metadataFormatSchemaUrl)); validMetadataFormats.add("-- SELECT FORMAT --"); List nodes = document.selectNodes("//xsd:simpleType[@name='itemFormatType']/xsd:restriction/xsd:enumeration"); for (Iterator iter = nodes.iterator(); iter.hasNext(); ) { Node node = (Node) iter.next(); validMetadataFormats.add(node.valueOf("@value")); } } catch (Throwable e) { prtlnErr("Error getValidMetadataFormats(): " + e); validMetadataFormats = null; } } return validMetadataFormats; }
@Override public Element getConfig() { final File boardFile = new File(getConfigFile()); if (boardFile.exists()) { try { return new SAXReader(false).read(boardFile).getRootElement(); } catch (DocumentException ex) { QLog.l().logger() .error("Невозможно прочитать файл конфигурации главного табло. " + ex .getMessage()); return DocumentHelper.createElement("Ответ"); } } else { QLog.l().logger() .warn("Файл конфигурации главного табло \"" + configFile + "\" не найден. "); return DocumentHelper.createElement("Ответ"); } }
/** * Grabs the collection keys from the DPC keys schema. * * @return A list of valid colleciton keys. */ public ArrayList getValidCollectionKeys() { String collectionKeySchemaUrl = getServlet().getServletContext().getInitParameter("collectionKeySchemaUrl"); if (collectionKeySchemaUrl == null) return null; if (validCollectionKeys == null) { try { validCollectionKeys = new ArrayList(); SAXReader reader = new SAXReader(); Document document = reader.read(new URL(collectionKeySchemaUrl)); validCollectionKeys.add("-- SELECT COLLECTION KEY --"); List nodes = document.selectNodes("//xsd:simpleType[@name='keyType']/xsd:restriction/xsd:enumeration"); for (Iterator iter = nodes.iterator(); iter.hasNext(); ) { Node node = (Node) iter.next(); validCollectionKeys.add(node.valueOf("@value")); } } catch (Throwable e) { prtlnErr("Error getCollectionKeys(): " + e); validCollectionKeys = null; } } return validCollectionKeys; }
private Document readDocument(String path,String name, int age) throws DocumentException{ SAXReader reader=new SAXReader(); Document document=reader.read(path); Element root=document.getRootElement(); List listOfTextView=document.selectNodes("view/body/form/textView"); for(Iterator<Element> i=listOfTextView.listIterator();i.hasNext();){ Element textView=i.next(); if(textView.selectSingleNode("name").getText().equals("userName")){ textView.selectSingleNode("value").setText(name); } if(textView.selectSingleNode("name").getText().equals("userAge")){ textView.selectSingleNode("value").setText(""+age); } } System.out.println(document); return document; }
/** * Get the packageId for the manifest file * * @param manifestFile * @return */ public static String getApplicationId(File manifestFile) { SAXReader reader = new SAXReader(); if (manifestFile.exists()) { Document document = null;// Read the XML file try { document = reader.read(manifestFile); Element root = document.getRootElement();// Get the root node String packageName = root.attributeValue("package"); return packageName; } catch (DocumentException e) { e.printStackTrace(); } } return null; }
/** * Update the plug-in's minSdkVersion and targetSdkVersion * * @param androidManifestFile * @throws IOException * @throws DocumentException */ public static String getVersionName(File androidManifestFile) throws IOException, DocumentException { SAXReader reader = new SAXReader(); String versionName = ""; if (androidManifestFile.exists()) { Document document = reader.read(androidManifestFile);// Read the XML file Element root = document.getRootElement();// Get the root node if ("manifest".equalsIgnoreCase(root.getName())) { List<Attribute> attributes = root.attributes(); for (Attribute attr : attributes) { if (StringUtils.equalsIgnoreCase(attr.getName(), "versionName")) { versionName = attr.getValue(); } } } } return versionName; }
public static String getVersionCode(File androidManifestFile) throws IOException, DocumentException { SAXReader reader = new SAXReader(); String versionCode = ""; if (androidManifestFile.exists()) { Document document = reader.read(androidManifestFile);// Read the XML file Element root = document.getRootElement();// Get the root node if ("manifest".equalsIgnoreCase(root.getName())) { List<Attribute> attributes = root.attributes(); for (Attribute attr : attributes) { if (StringUtils.equalsIgnoreCase(attr.getName(), "versionCode")) { versionCode = attr.getValue(); } } } } return versionCode; }
/** * 摸查项目输出目录 * <p> * @param projectPath * @param kind output 或 src * @return */ public static String readXML(String projectPath, String kind) { try { SAXReader saxReader = new SAXReader(); File classpath = new File(projectPath + "/.classpath"); if (classpath.exists()) { Document document = saxReader.read(classpath); List<Element> out = (List<Element>) document.selectNodes("/classpath/classpathentry[@kind='" + kind + "']"); String tmp = ""; for (Element out1 : out) { String combineaccessrules = out1.attributeValue("combineaccessrules"); if ("false".equals(combineaccessrules) && "src".equals(kind)) { continue; } tmp += out1.attributeValue("path") + ","; } return tmp.isEmpty() ? tmp : tmp.substring(0, tmp.length() - 1); } } catch (DocumentException ex) { MainFrame.LOGGER.log(Level.SEVERE, null, ex); JOptionPane.showMessageDialog(null, ex.getLocalizedMessage()); } return ""; }
/** * 删除配置 * * @param name * @throws Exception */ public static void removeHttpConfig(String name) throws Exception { SAXReader reader = new SAXReader(); File xml = new File(HTTP_CONFIG_FILE); Document doc; Element root; try (FileInputStream in = new FileInputStream(xml); Reader read = new InputStreamReader(in, "UTF-8")) { doc = reader.read(read); root = doc.getRootElement(); Element cfg = (Element) root.selectSingleNode("/root/configs"); Element e = (Element) root.selectSingleNode("/root/configs/config[@name='" + name + "']"); if (e != null) { cfg.remove(e); CONFIG_MAP.remove(name); } OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding("UTF-8"); XMLWriter writer = new XMLWriter(new FileOutputStream(xml), format); writer.write(doc); writer.close(); } }
protected DatabaseUpdate() throws Exception { Document document = null; String dbUpdateFile = findDbUpdateFileName(); URL dbUpdateFileUrl = ApplicationProperties.class.getClassLoader().getResource(dbUpdateFile); if (dbUpdateFileUrl!=null) { Debug.info("Reading " + URLDecoder.decode(dbUpdateFileUrl.getPath(), "UTF-8") + " ..."); document = (new SAXReader()).read(dbUpdateFileUrl.openStream()); } else if (new File(dbUpdateFile).exists()) { Debug.info("Reading " + dbUpdateFile + " ..."); document = (new SAXReader()).read(new File(dbUpdateFile)); } if (document==null) { sLog.error("Unable to execute " + updateName() + " database auto-update, reason: resource "+dbUpdateFile+" not found."); return; } if (!"dbupdate".equals(document.getRootElement().getName())) throw new Exception("Unknown format."); iRoot = document.getRootElement(); }
protected Document receiveResponse() throws IOException, DocumentException { try { SessionImplementor session = (SessionImplementor)new _RootDAO().getSession(); Connection connection = session.getJdbcConnectionAccess().obtainConnection(); String response = null; try { CallableStatement call = connection.prepareCall(iResponseSql); call.registerOutParameter(1, java.sql.Types.CLOB); call.execute(); response = call.getString(1); call.close(); } finally { session.getJdbcConnectionAccess().releaseConnection(connection); } if (response==null || response.length()==0) return null; StringReader reader = new StringReader(response); Document document = (new SAXReader()).read(reader); reader.close(); return document; } catch (Exception e) { sLog.error("Unable to receive response: "+e.getMessage(),e); return null; } finally { _RootDAO.closeCurrentThreadSessions(); } }
public void init(FilterConfig cfg) throws ServletException { iContext = cfg.getServletContext(); try { Document config = (new SAXReader()).read(cfg.getServletContext().getResource(cfg.getInitParameter("config"))); for (Iterator i=config.getRootElement().element("action-mappings").elementIterator("action"); i.hasNext();) { Element action = (Element)i.next(); String path = action.attributeValue("path"); String input = action.attributeValue("input"); if (path!=null && input!=null) { iPath2Tile.put(path+".do", input); } } } catch (Exception e) { sLog.error("Unable to read config "+cfg.getInitParameter("config")+", reason: "+e.getMessage()); } if (cfg.getInitParameter("debug-time")!=null) { debugTime = Long.parseLong(cfg.getInitParameter("debug-time")); } if (cfg.getInitParameter("dump-time")!=null) { dumpTime = Long.parseLong(cfg.getInitParameter("dump-time")); } if (cfg.getInitParameter("session-attributes")!=null) { dumpSessionAttribues = Boolean.parseBoolean(cfg.getInitParameter("session-attributes")); } }
/** * @param args the command line arguments */ public static void main(String[] args) { QLog.initial(args, 17); Locale.setDefault(Locales.getInstance().getLangCurrent()); // проверить есть ли файл /config/clientboard.xml и если есть отправить его на редактирование if (args.length < 2) { throw new ServerException("No param '-tcfg' file for context."); } file = new File(QConfig.cfg().getTabloBoardCfgFile()); if (!file.exists()) { throw new ServerException( "File context \"" + QConfig.cfg().getTabloBoardCfgFile() + "\" not exist."); } QLog.l().logger().info("Load file: " + file.getAbsolutePath()); final SAXReader reader = new SAXReader(false); try { root = reader.read(file).getRootElement(); } catch (DocumentException ex) { throw new ServerException("Wrong xml file. " + ex.getMessage()); } /* java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() {*/ final FBoardConfig bc = new FBoardConfigImpl(null, false); bc.setTitle(bc.getTitle() + " " + file.getAbsolutePath()); bc.setParams(root); Uses.setLocation(bc); bc.setVisible(true); /* } });*/ }
private void startParseXML(Path xmlPath) throws Exception { String xml = getXMLContent(xmlPath); SAXReader reader = new SAXReader(); Document doc = reader.read(new ByteArrayInputStream(xml.getBytes("UTF-8"))); Element rooElem = doc.getRootElement(); getChildNodes(rooElem, ""); }
/** * 解析xml文档 * @param inputStream * @param row * @throws DocumentException */ private void parse(InputStream inputStream, int row) throws DocumentException { Document document = new SAXReader().read(inputStream); parse(document, row); }
/** * 根据给定的XML文件解析出Excel的结构 */ public static ExcelStruct parseImportStruct(String xmlFile) throws DocumentException, IOException { if (StringUtils.isEmpty(xmlFile)) { return null; } InputStream is = new FileInputStream(new File(xmlFile)); if (is == null) { throw new FileNotFoundException("Excel的描述文件 : " + xmlFile + " 未找到."); } SAXReader saxReader = new SAXReader(); Document document = saxReader.read(is); // 根节点 Element root = document.getRootElement(); // 一次导入 List onceList = root.elements("onceImport"); // 重复导入 List repeatList = root.elements("repeatImport"); // 校验器的定义 List validators = root.elements("validators"); // 单元格校验 List cellValidators = root.elements("cell-validators"); ExcelStruct excelStruct = new ExcelStruct(); // 读取校验器配置 parseValidatorConfig(excelStruct, validators, cellValidators); // 获取需要一次性导入的xml解析文件 simpleParseOnceImport(excelStruct, onceList); // 获取excel重复读取的xml解析文件 simpleParseRepeatImport(excelStruct, repeatList); is.close(); return excelStruct; }
@Before public void setUp() throws Exception { InputStream is = new FileInputStream(new File(xmlFile)); if (is == null) { throw new FileNotFoundException("Excel的描述文件 : " + xmlFile + " 未找到."); } SAXReader saxReader = new SAXReader(); Document document = saxReader.read(is); // 根节点 Element root = document.getRootElement(); // 一次导入 onceList = root.elements("onceImport"); // 重复导入 List repeatList = root.elements("repeatImport"); // 校验器的定义 List validators = root.elements("validators"); // 单元格校验 List cellValidators = root.elements("cell-validators"); excelStruct = new ExcelStruct(); // 读取校验器配置 // parseValidatorConfig(excelStruct, validators, cellValidators); // simpleParseOnceImport(excelStruct, onceList); is.close(); }
public ModifyXML(String filePath) { try { File inputFile = new File(filePath); SAXReader reader = new SAXReader(); document = reader.read(inputFile); } catch (DocumentException e) { e.printStackTrace(); } }
public ModifyXML(File inputFile) { try { SAXReader reader = new SAXReader(); document = reader.read(inputFile); } catch (DocumentException e) { e.printStackTrace(); } }
public static Map<String, Object> xml2Map(String xml){ SAXReader saxReader = new SAXReader(); Document doc; try { doc = saxReader.read(new StringReader(xml)); return document2Map(doc); } catch (DocumentException e) { e.printStackTrace(); return null; } }
public static Map<String, String> xmlToMap(HttpServletRequest request) throws IOException, DocumentException { Map<String, String> rtnMap = new HashMap<>(); SAXReader reader = new SAXReader(); try (ServletInputStream in = request.getInputStream()) { Document root = reader.read(in); Element rootElement = root.getRootElement(); List<Element> elements = rootElement.elements(); elements.forEach(e -> rtnMap.put(e.getName(), e.getText())); } return rtnMap; }
private InputStream processModelDocType(InputStream is, String dtdSchemaUrl) throws DocumentException, IOException { SAXReader reader = new SAXReader(); // read document without validation Document doc = reader.read(is); DocumentType docType = doc.getDocType(); if (docType != null) { // replace DOCTYPE setting the full path to the xsd docType.setSystemID(dtdSchemaUrl); } else { // add the DOCTYPE docType = new DefaultDocumentType(doc.getRootElement().getName(), dtdSchemaUrl); doc.setDocType(docType); } ByteArrayOutputStream fos = new ByteArrayOutputStream(); try { OutputFormat format = OutputFormat.createPrettyPrint(); // uses UTF-8 XMLWriter writer = new XMLWriter(fos, format); writer.write(doc); writer.flush(); } finally { fos.close(); } return new ByteArrayInputStream(fos.toByteArray()); }
private void init( String xmlText ) throws XMLException { Document document = null; try { document = new SAXReader().read(new StringReader(xmlText)); } catch (DocumentException e) { throw new XMLException("Error parsing XML text:\n" + xmlText, e); } this.root = document.getRootElement(); }
/** * Removes the given OAI set definition from the ListSets config XML file and writes it to disc. * * @param setsConfigFile The ListSets config file * @param setSpec The set to remove * @return True if the set existed and was removed * @exception Exception If error */ public static boolean removeOAISetSpecDefinition(File setsConfigFile, String setSpec) throws Exception { Document document = null; if (setsConfigFile == null || !setsConfigFile.exists()) return false; // Create the XML DOM if (setsConfigFile.exists()) { SAXReader reader = new SAXReader(); document = reader.read(setsConfigFile); } Element root = document.getRootElement(); if (!root.getName().equals("ListSets")) throw new Exception("OAI Sets XML is incorrect. Root node is not 'ListSets'"); // Remove the previous set definition, if present String xPath = "set[setSpec=\"" + setSpec + "\"]"; Element prevSet = (Element) root.selectSingleNode(xPath); if (prevSet == null) return false; root.remove(prevSet); // Write the XML to disc OutputFormat format = OutputFormat.createPrettyPrint(); XMLWriter writer = new XMLWriter(new FileWriter(setsConfigFile), format); writer.write(document); writer.close(); return true; }
/** * 通过XSD(XML Schema)校验XML */ @Test public void validateXMLByXSD() { String path = this.getClass().getResource("/").getPath(); int index = path.lastIndexOf("/"); path = path.substring(0, index); String xmlFileName = path + "/processCore.xml"; // String xsdFileName = // "/Users/user/workspace/bulbasaur/core/src/test/resources/process_bak.xsd"; String xsdFileName = path + "/test.xsd"; 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 = xmlReader.read(new File(xmlFileName)); // 设置 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文件通过XSD文件校验失败!"); writer.write(errorHandler.getErrors()); } else { System.out.println("Good! XML文件通过XSD文件校验成功!"); } } catch (Exception ex) { System.out.println("XML文件: " + xmlFileName + " 通过XSD文件:" + xsdFileName + "检验失败。\n原因: " + ex.getMessage()); ex.printStackTrace(); } }
/** * Load XML File, Read it into Document * @param filename * The Name of the file which will be analysis */ public Document loadXML(final String filename) { //Document document = null; try { final SAXReader saxReader = new SAXReader(); document = saxReader.read(new File(filename)); } catch (final Exception ex) { ex.printStackTrace(); } return document; }