public static void addToFlex(String name) { SAXReader reader = new SAXReader(); Document document; try { document = reader.read(new File(FLEX_CONFIG)); Element flex = document.getRootElement(); // Flex------------------------------------------------------------- Element destination = flex.addElement("destination"); destination.addAttribute("id", name); Element properties = destination.addElement("properties"); Element factory = properties.addElement("factory"); Element source = properties.addElement("source"); factory.addText("springFactory"); source.addText(Tools.firstLowcase(name)); // 更新保存---------------------------------------------------- XMLWriter writer = new XMLWriter(new FileWriter(FLEX_CONFIG)); writer.write(document); writer.close(); } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
@Override public Document getXmlContent() { // get the data to populate the widgets IPentahoResultSet resultSet = null; if (solution != null) { resultSet = getActionData(); } else { // TODO support other methods of getting data } // create the widget to use // load the XML document that defines the dial Document dialDefinition = null; try { org.dom4j.io.SAXReader reader = new org.dom4j.io.SAXReader(); reader.setEntityResolver(new SolutionURIResolver()); dialDefinition = reader.read( ActionSequenceResource.getInputStream(definitionPath, LocaleHelper.getLocale())); } catch (Throwable t) { // XML document can't be read. We'll just return a null document. } // create a dial definition from the XML definition WidgetDefinition widgetDefinition = new DialWidgetDefinition(dialDefinition, 0, widgetWidth, widgetHeight, getSession()); return createDials(resultSet, widgetDefinition); }
public void testAll() throws Exception { XMLHelper xmlHelper = new XMLHelper(); ClassLoader cl = Thread.currentThread().getContextClassLoader(); InputStream is = cl.getResourceAsStream("org/hibernate/test/annotations/reflection/orm.xml"); assertNotNull("ORM.xml not found", is); XMLContext context = new XMLContext(); List errors = new ArrayList(); SAXReader saxReader = xmlHelper.createSAXReader("XML InputStream", errors, EJB3DTDEntityResolver.INSTANCE); // saxReader.setValidation( false ); try { saxReader.setFeature("http://apache.org/xml/features/validation/schema", true); } catch (SAXNotSupportedException e) { saxReader.setValidation(false); } org.dom4j.Document doc; try { doc = saxReader.read(new InputSource(new BufferedInputStream(is))); } finally { try { is.close(); } catch (IOException ioe) { // log.warn( "Could not close input stream", ioe ); } } assertEquals(0, errors.size()); context.addDocument(doc); }
public void testWithMultiList() throws Exception { List list = new ArrayList(); list.add(Country.COUNTRY_UK); list.add(Country.COUNTRY_AT); this.bean.setSomeList(list); this.tag.setPath("someList"); this.tag.setItems("${countries}"); this.tag.setItemValue("isoCode"); int result = this.tag.doStartTag(); assertEquals(Tag.SKIP_BODY, result); String output = getWriter().toString(); output = "<doc>" + output + "</doc>"; SAXReader reader = new SAXReader(); Document document = reader.read(new StringReader(output)); Element rootElement = document.getRootElement(); assertEquals(2, rootElement.elements().size()); Element selectElement = rootElement.element("select"); assertEquals("select", selectElement.getName()); assertEquals("someList", selectElement.attribute("name").getValue()); List children = selectElement.elements(); assertEquals("Incorrect number of children", 4, children.size()); String hdivValue = this.confidentiality ? "3" : "UK"; Element e = (Element) selectElement.selectSingleNode("option[@value = '" + hdivValue + "']"); assertEquals("UK node not selected", "selected", e.attribute("selected").getValue()); hdivValue = this.confidentiality ? "1" : "AT"; e = (Element) selectElement.selectSingleNode("option[@value = '" + hdivValue + "']"); assertEquals("AT node not selected", "selected", e.attribute("selected").getValue()); }
public void testMultiWithEmptyCollection() throws Exception { this.bean.setSomeList(new ArrayList()); this.tag.setPath("someList"); this.tag.setItems("${countries}"); this.tag.setItemValue("isoCode"); int result = this.tag.doStartTag(); assertEquals(Tag.SKIP_BODY, result); String output = getWriter().toString(); output = "<doc>" + output + "</doc>"; SAXReader reader = new SAXReader(); Document document = reader.read(new StringReader(output)); Element rootElement = document.getRootElement(); assertEquals(2, rootElement.elements().size()); Element selectElement = rootElement.element("select"); assertEquals("select", selectElement.getName()); assertEquals("someList", selectElement.attribute("name").getValue()); assertEquals("multiple", selectElement.attribute("multiple").getValue()); List children = selectElement.elements(); assertEquals("Incorrect number of children", 4, children.size()); Element inputElement = rootElement.element("input"); assertNotNull(inputElement); }
@SuppressWarnings("unchecked") public static Properties getProperties(String persistenceFile, String persistenceUnit) { Properties properties = new Properties(); SAXReader reader = new SAXReader(); InputStream is = null; try { Document doc; is = XMLPersistenceUtil.class.getClassLoader().getResourceAsStream(persistenceFile); doc = reader.read(is); Element root = doc.getRootElement(); List<Element> elements = root.elements(); for (Element el : elements) { if (persistenceUnit.equals(el.attributeValue("name"))) { // this is the persistence unit specified, let's get all properties inside Element propsElement = el.element("properties"); List<Element> xmlProps = propsElement.elements("property"); for (Element prop : xmlProps) { properties.put(prop.attributeValue("name"), prop.attributeValue("value")); } } } } catch (DocumentException e) { _log.error("Failed to read file contents for " + persistenceFile, e); return null; } finally { if (is != null) try { is.close(); } catch (Exception e) { // do nothing } ; } return properties; }
public static BufferedImage drawDistrictsByZipCode( String countryFile, int totalcolors, double min, double max, String[][] districts) { String cf = ""; SAXReader reader = new SAXReader(false); try { String sDoc = MedwanQuery.getInstance().getConfigString("templateSource") + countryFile; Document document = reader.read(new URL(sDoc)); Element root = document.getRootElement(); cf = root.attributeValue("directory") + "/" + root.attributeValue("countrymap"); } catch (Exception e) { if (Debug.enabled) Debug.println(e.getMessage()); } BufferedImage resultImage = toBufferedImage(Miscelaneous.getImage(cf)); for (int n = 0; n < districts.length; n++) { if (districts[n] != null) { District district = District.getDistrictWithZipcode(countryFile, districts[n][0]); if (district != null) { BufferedImage im1 = toBufferedImage( replaceColor( Miscelaneous.getImage(district.getMap()), 0xffff0000, getColor(totalcolors, min, max, Double.parseDouble(districts[n][1])))); resultImage = createComposite(resultImage, im1, 1f); } } } return resultImage; }
public static void exportDiffFiles(String diffXmlFile, String targetDir) throws Exception { SAXReader reader = new SAXReader(); Document document = reader.read(new File(diffXmlFile)); Element rootElement = document.getRootElement(); Element rootFolder = rootElement.element(DiffXmlReader.TAG_FOLDER_COMP); Element ltpathElement = rootFolder.element(DiffXmlReader.TAG_LTPATH); String baseDir = ltpathElement.getTextTrim() + File.separator; List<String> diffList = DiffXmlReader.readDiffList(document); for (String path : diffList) { if (path.indexOf(File.separator + "test") != -1 || path.indexOf(File.separator + "build") != -1) { continue; } File file = new File(path); String dir = file.getParent(); String relativeDir = dir.substring(baseDir.length()); String targetFolder = targetDir + relativeDir; File folder = new File(targetFolder); if (!folder.exists()) { folder.mkdirs(); } FileUtils.copyFileToDirectory(file, folder); } }
/** * 用于防钓鱼,调用接口query_timestamp来获取时间戳的处理函数 注意:远程解析XML出错,与服务器是否支持SSL等配置有关 * * @return 时间戳字符串 * @throws IOException * @throws DocumentException * @throws MalformedURLException */ @SuppressWarnings("unchecked") 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(); }
private StatusAndRecords getStatusAndRecordsFromLogFile(String dataSetId, String logFileName) { File logFile = new File( ConfigSingleton.getRepoxContextUtil() .getRepoxManager() .getConfiguration() .getRepositoryPath() + File.separator + dataSetId + File.separator + "logs" + File.separator + logFileName); try { SAXReader reader = new SAXReader(); Document logDocument = reader.read(logFile); String status = logDocument.valueOf("//report/status"); String records = logDocument.valueOf("//report/records"); return new StatusAndRecords(status, records); } catch (DocumentException e) { return new StatusAndRecords("OK", "0"); } }
public void testHiddenElementOmittedOnDisabled() throws Exception { this.tag.setPath("stringArray"); this.tag.setItems(new Object[] {"foo", "bar", "baz"}); this.tag.setDisabled("true"); int result = this.tag.doStartTag(); assertEquals(Tag.SKIP_BODY, result); String output = getOutput(); // wrap the output so it is valid XML output = "<doc>" + output + "</doc>"; SAXReader reader = new SAXReader(); Document document = reader.read(new StringReader(output)); Element rootElement = document.getRootElement(); assertEquals( "Both tag and hidden element rendered incorrectly", 3, rootElement.elements().size()); Element spanElement = (Element) document.getRootElement().elements().get(0); Element checkboxElement = (Element) spanElement.elements().get(0); assertEquals("input", checkboxElement.getName()); assertEquals("checkbox", checkboxElement.attribute("type").getValue()); assertEquals("stringArray", checkboxElement.attribute("name").getValue()); assertEquals("checked", checkboxElement.attribute("checked").getValue()); assertEquals("disabled", checkboxElement.attribute("disabled").getValue()); assertEquals("foo", checkboxElement.attribute("value").getValue()); }
/** * 格式化xml * * @param xml * @return */ public static String formatXML(String xml) { SAXReader reader = null; XMLWriter writer = null; StringWriter stringWriter = null; try { reader = new SAXReader(); org.dom4j.Document document = reader.read(new StringReader(xml)); if (document != null) { stringWriter = new StringWriter(); OutputFormat format = new OutputFormat(" ", false); format.setSuppressDeclaration(true); writer = new XMLWriter(stringWriter, format); writer.write(document); writer.flush(); } return stringWriter.getBuffer().toString(); } catch (Exception e) { LOG.error("格式化xml失败", e); } finally { try { writer.close(); stringWriter.close(); } catch (Exception e) { // ignore } } return xml; }
public boolean init() { if (filterPanel == null) { // load the XML document that defines the dial Document filterDocument = null; try { org.dom4j.io.SAXReader reader = new org.dom4j.io.SAXReader(); reader.setEntityResolver(new SolutionURIResolver()); filterDocument = reader.read( ActionSequenceResource.getInputStream(definitionPath, LocaleHelper.getLocale())); } catch (Throwable t) { FilterPanelComponent.logger.error( Messages.getInstance().getString("FilterPanelComponent.ERROR_0002_CREATE_XML"), t); //$NON-NLS-1$ return false; } try { filterPanel = getFilterPanel(filterDocument); } catch (FilterPanelException e) { // TODO sbarkdull localize FilterPanelComponent.logger.error( Messages.getInstance().getString("FilterPanelComponent.ERROR_0003_CREATE"), e); //$NON-NLS-1$ return false; } } return true; }
/** 功能:XML报文解析函数 */ public static HashMap GetMessage(String url) { SAXReader reader = new SAXReader(); Document doc = null; HashMap hm = null; try { InputStream in = new URL(url).openStream(); if (in != null) { doc = reader.read(in); hm = new HashMap(); Element root = doc.getRootElement(); for (Iterator it = root.elementIterator(); it.hasNext(); ) { Element e = (Element) it.next(); if (e.nodeCount() > 1) { HashMap hm1 = new HashMap(); for (Iterator it1 = e.elementIterator(); it1.hasNext(); ) { Element e1 = (Element) it1.next(); hm1.put(e1.getName(), e1.getText()); } hm.put(e.getName(), hm1); } else { hm.put(e.getName(), e.getText()); } } } doc.clearContent(); in.close(); } catch (DocumentException e) { e.printStackTrace(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return hm; }
/** * 根据路径获取dom4j * * @param path * @return */ private Document getDocument(String path) { Document doc = null; InputStream in = null; if (path == null) { throw new CantfindConfigFileByPathException(null); } path = path.trim(); if (path.equals("")) { throw new CantfindConfigFileByPathException(path); } try { in = TDLXmlParser.class.getResourceAsStream(path); if (in == null) { try { in = new FileInputStream(new File(path)); } catch (FileNotFoundException e) { throw new TDLRunTimeException( "指定的mapping文件不正确,所指定路径为:" + path + "" + "若使用/filename,则会从path的class根目录上去找资源,一般使用这个即可" + "若使用filename,则会从类的相对目录去寻找资源,如果不能找到,也会尝试使用File的方式来找", e); } } Reader read = new InputStreamReader(in); SAXReader reader = new SAXReader(); doc = reader.read(read); } catch (DocumentException e) { throw new TDLRunTimeException("解析映射文件时发生错误,请检查映射文件", e); } return doc; }
private ProjectDefinitionTO readProjectDefinition(String fileName) throws DocumentException { SAXReader reader = new SAXReader(); Document document = reader.read(new File(fileName)); return null; }
public static Map<String, Object> get(String url, String encoding) throws Exception { SAXReader reader = new SAXReader(); Document document = reader.read(new URL(url)); Map<String, Object> map = new HashMap<>(); elementToMap(map, document.getRootElement()); return map; }
/* * 参数 : userid:用户名 password:密码 destnumbers 发送号码 msg 发送内容 sendtime发送时间 返回值 * : XML格式,UTF-8编码 说明: 1. destnumbers 发送号码最大一次提交200个,号码用任意分隔符分开. 2. * 发送号码移动,联通,小灵通可以混和提交 3. 如当前账号不支持某网络发送在QueryUserInfo返回中 /root/ * maxchars_xx 的值为0 4. 如当前账号不支持某网络的发送同时又提交了此网络的号码会报错5.号码错误 5. * msg发送内容最大250个字符,不分区中英文. 6. 发送内容大于相应网络的最大字符数(/root/ * maxchars_xx)时系统拆成多条发送 7. 每条短信后自动加上用户注册的签名:如 [满堂红] 8. * 不加sendtime参数或值为“”时短信立即发送,如果要定制发送时间则加sendtime参数格式为 YYYY-MM-DD HH:MM:SS * 如:2008-05-12 10:00:00 调用成功时: <root return="0" info="成功" msgid="{短信批号}" * numbers="{ 总计号码个数}" messages="{ 总计短信条数}"> </root> 例如: 发一个移动号码,内容不分段的返回 * <root return="0" info="成功" msgid=“FI293EF2D002F01D” numbers="1" * messages="1"> </root> */ public HashMap sendDone(String destnumbers, String msg, String sendtime) throws Exception { String qUrl = url + "?userid=" + userId + "&password="******"UTF-8") + "&destnumbers=" + destnumbers + "&msg=" + java.net.URLEncoder.encode(msg, "UTF-8"); if (!StringUtils.isBlank(sendtime)) { qUrl += "&sendtime=" + sendtime; } // 这里用了 dom4j 来分析返回的XML org.dom4j.io.SAXReader reader = new org.dom4j.io.SAXReader(); org.dom4j.Document doc = reader.read(new java.net.URL(qUrl)); HashMap map = new HashMap(); map.put("return", doc.valueOf("/root/@return")); map.put("info", doc.valueOf("/root/@info")); map.put("msgid", doc.valueOf("/root/@msgid")); return map; }
public static BufferedImage drawDistrictsById( String countryFile, int totalcolors, double min, double max, double[][] districts) { String cf = ""; SAXReader reader = new SAXReader(false); try { String sDoc = Constants.CLASSPATH + "/xml/" + countryFile; Document document = reader.read(new URL(sDoc)); Element root = document.getRootElement(); cf = root.attributeValue("directory") + "/" + root.attributeValue("countrymap"); } catch (Exception e) { if (Debug.enabled) Debug.println(e.getMessage()); } BufferedImage resultImage = toBufferedImage(Miscelaneous.getImage(cf)); for (int n = 0; n < districts.length; n++) { if (districts[n] != null) { District district = District.getDistrictWithId(countryFile, new Double(districts[n][0]).intValue() + ""); if (district != null) { int color = getColor(totalcolors, min, max, districts[n][1]); BufferedImage im1 = toBufferedImage( replaceColor(Miscelaneous.getImage(district.getMap()), 0xffff0000, color)); resultImage = createComposite(resultImage, im1, 1f); } } } return resultImage; }
/** * 修改xml某节点的值 * * @param inputXml 原xml文件 * @param nodes 要修改的节点 * @param attributename 属性名称 * @param value 新值 * @param outXml 输出文件路径及文件名 如果输出文件为null,则默认为原xml文件 */ public static void modifyDocument( File inputXml, String nodes, String attributename, String value, String outXml) { try { SAXReader saxReader = new SAXReader(); Document document = saxReader.read(inputXml); List list = document.selectNodes(nodes); Iterator iter = list.iterator(); while (iter.hasNext()) { Attribute attribute = (Attribute) iter.next(); if (attribute.getName().equals(attributename)) attribute.setValue(value); } XMLWriter output; if (outXml != null) { // 指定输出文件 output = new XMLWriter(new FileWriter(new File(outXml))); } else { // 输出文件为原文件 output = new XMLWriter(new FileWriter(inputXml)); } output.write(document); output.close(); } catch (DocumentException e) { System.out.println(e.getMessage()); } catch (IOException e) { System.out.println(e.getMessage()); } }
public void testWithIntegerArray() throws Exception { this.tag.setPath("someIntegerArray"); Integer[] array = new Integer[50]; for (int i = 0; i < array.length; i++) { array[i] = new Integer(i); } this.tag.setItems(array); int result = this.tag.doStartTag(); assertEquals(Tag.SKIP_BODY, result); String output = getWriter().toString(); output = "<doc>" + output + "</doc>"; SAXReader reader = new SAXReader(); Document document = reader.read(new StringReader(output)); Element rootElement = document.getRootElement(); assertEquals(2, rootElement.elements().size()); Element selectElement = rootElement.element("select"); assertEquals("select", selectElement.getName()); assertEquals("someIntegerArray", selectElement.attribute("name").getValue()); List children = selectElement.elements(); assertEquals("Incorrect number of children", array.length, children.size()); Element e = (Element) selectElement.selectSingleNode("option[text() = '12']"); assertEquals("'12' node not selected", "selected", e.attribute("selected").getValue()); e = (Element) selectElement.selectSingleNode("option[text() = '34']"); assertEquals("'34' node not selected", "selected", e.attribute("selected").getValue()); }
private String _buildPramatiXMLWebModule(String path) throws DocumentException, IOException { String contextRoot = path.substring(2, path.length() - 4); String filePath = path + "/docroot/WEB-INF/web.xml"; if (path.endsWith("-complete")) { contextRoot = "/"; filePath = path.substring(0, path.length() - 9) + "/docroot/WEB-INF/web.xml"; } FastStringBuffer sb = new FastStringBuffer(); sb.append("\t<web-module>\n"); sb.append("\t\t<name>").append(contextRoot).append("</name>\n"); sb.append("\t\t<module-name>") .append(path.substring(3, path.length())) .append(".war</module-name>\n"); SAXReader reader = new SAXReader(); reader.setEntityResolver(new EntityResolver()); Document doc = reader.read(new File(filePath)); Iterator itr = doc.getRootElement().elements("ejb-local-ref").iterator(); while (itr.hasNext()) { Element ejbLocalRef = (Element) itr.next(); sb.append("\t\t<ejb-local-ref>\n"); sb.append("\t\t\t<ejb-ref-name>") .append(ejbLocalRef.elementText("ejb-ref-name")) .append("</ejb-ref-name>\n"); sb.append("\t\t\t<ejb-link>") .append(ejbLocalRef.elementText("ejb-link")) .append("</ejb-link>\n"); sb.append("\t\t</ejb-local-ref>\n"); } itr = doc.getRootElement().elements("resource-ref").iterator(); while (itr.hasNext()) { Element resourceRef = (Element) itr.next(); sb.append("\t\t<resource-mapping>\n"); sb.append("\t\t\t<resource-name>") .append(resourceRef.elementText("res-ref-name")) .append("</resource-name>\n"); sb.append("\t\t\t<resource-type>") .append(resourceRef.elementText("res-type")) .append("</resource-type>\n"); sb.append("\t\t\t<resource-link>") .append(resourceRef.elementText("res-ref-name")) .append("</resource-link>\n"); sb.append("\t\t</resource-mapping>\n"); } sb.append("\t</web-module>\n"); return sb.toString(); }
public void testWithMultiMap() throws Exception { Map someMap = new HashMap(); someMap.put("M", "Male"); someMap.put("F", "Female"); this.bean.setSomeMap(someMap); this.tag.setPath("someMap"); this.tag.setItems("${sexes}"); int result = this.tag.doStartTag(); assertEquals(Tag.SKIP_BODY, result); String output = getWriter().toString(); output = "<doc>" + output + "</doc>"; SAXReader reader = new SAXReader(); Document document = reader.read(new StringReader(output)); Element rootElement = document.getRootElement(); assertEquals(2, rootElement.elements().size()); Element selectElement = rootElement.element("select"); assertEquals("select", selectElement.getName()); assertEquals("someMap", selectElement.attribute("name").getValue()); List children = selectElement.elements(); assertEquals("Incorrect number of children", 2, children.size()); String hdivValue = this.confidentiality ? "1" : "M"; Element e = (Element) selectElement.selectSingleNode("option[@value = '" + hdivValue + "']"); assertEquals("M node not selected", "selected", e.attribute("selected").getValue()); hdivValue = this.confidentiality ? "2" : "F"; e = (Element) selectElement.selectSingleNode("option[@value = '" + hdivValue + "']"); assertEquals("F node not selected", "selected", e.attribute("selected").getValue()); }
private void loadDbConf(String dbConfClassPath) { try { ClassLoader loader = Thread.currentThread().getContextClassLoader(); InputStream confInput = loader.getResourceAsStream(dbConfClassPath); SAXReader reader = new SAXReader(); Document doc = reader.read(confInput); Element root = doc.getRootElement(); this.timeBetweenEvictionRunsMillis = Long.parseLong(root.elementText("timeBetweenEvictionRunsMillis")); this.maxActive = Integer.parseInt(root.elementText("maxActive")); this.maxIdle = Integer.parseInt(root.elementText("maxIdle")); this.maxWait = Integer.parseInt(root.elementText("maxWait")); this.testWhileIdle = Boolean.parseBoolean(root.elementText("maxActive")); Element masterEle = root.element("masters"); Map<String, DbInfo> masterDbInfoMap = this.parseDbInfo(masterEle.elements()); Element slavesEle = root.element("slaves"); Map<String, DbInfo> slaveDbInfoMap = this.parseDbInfo(slavesEle.elements()); this.checkMasterSlave(masterDbInfoMap, slaveDbInfoMap); this.masterDbInfoMap.putAll(masterDbInfoMap); this.slaveDbInfoMap.putAll(slaveDbInfoMap); } catch (Exception e) { throw new RuntimeException("loadDbConf failed !" + e.getMessage()); } }
@Test public void html() throws Exception { String subject = "html"; buildSMTPAppender(subject, SYNCHRONOUS); smtpAppender.setAsynchronousSending(false); smtpAppender.setLayout(buildHTMLLayout()); smtpAppender.start(); logger.addAppender(smtpAppender); logger.debug("html"); logger.error("en error", new Exception("an exception")); MimeMultipart mp = verifyAndExtractMimeMultipart(subject); // verifyAndExtractMimeMultipart strict adherence to xhtml1-strict.dtd SAXReader reader = new SAXReader(); reader.setValidation(true); reader.setEntityResolver(new XHTMLEntityResolver()); byte[] messageBytes = getAsByteArray(mp.getBodyPart(0).getInputStream()); ByteArrayInputStream bais = new ByteArrayInputStream(messageBytes); try { reader.read(bais); } catch (DocumentException de) { System.out.println("incoming message:"); System.out.println(new String(messageBytes)); throw de; } }
public static void main(String[] args) { try { Records records = new Records(); List<RecordBean> recordList = new ArrayList<RecordBean>(); SAXReader saxReader = new SAXReader(); Document document = saxReader.read("test.xml"); Element root = document.getRootElement(); List<Element> elements = root.selectNodes("//RECORD"); System.out.println(elements.size()); for (Element element : elements) { RecordBean recordBean = new RecordBean(); recordBean.setAuthor(element.elementText("FRatingNum")); recordBean.setImage(element.elementText("FDesc")); recordBean.setTitle(element.elementText("FTitle")); recordBean.setItemId(element.elementText("FItemId")); recordList.add(recordBean); } records.setRecords(recordList); JSONObject jsonObject = JSONObject.fromObject(records); System.out.println(jsonObject.toString()); } catch (DocumentException e) { e.printStackTrace(); } }
/** * 根据xml文件对象获得其Document对象 * * @param xmlFile 待解析的XML文件对象 * @return document对象 * @throws IOException */ public static Document getDocumentFromFile(File xmlFile) throws IOException { if (!xmlFile.exists()) { throw new FileNotFoundException("file " + xmlFile + " does not exist!"); } else if (xmlFile.isDirectory()) { throw new IOException("file " + xmlFile + " exists but is a directory!"); } else if (xmlFile.canRead() == false) { throw new IOException("file " + xmlFile + " cannot be read!"); } Document document = null; SAXReader saxReader = new SAXReader(); try { setReaderValidation(saxReader); document = saxReader.read(xmlFile); String namespace_uri = document.getRootElement().getNamespaceURI(); if (!StringUtils.isEmptyString(namespace_uri)) { setReadernameSpace(saxReader, namespace_uri); } } catch (DocumentException e) { e.printStackTrace(); } return document; }
@Test public void testHtmlWithTags() throws Exception { final String htmlText = "<html><head><title>Title</title></head>" + "<body><p>this is a test</p></body></html>"; // Create FetchedDatum using data String url = "http://domain.com/page.html"; String contentType = "text/html; charset=utf-8"; HttpHeaders headers = new HttpHeaders(); headers.add(HttpHeaderNames.CONTENT_TYPE, contentType); ContentBytes content = new ContentBytes(htmlText.getBytes("utf-8")); FetchedDatum fetchedDatum = new FetchedDatum(url, url, System.currentTimeMillis(), headers, content, contentType, 0); // Call parser.parse SimpleParser parser = new SimpleParser(new ParserPolicy(), true); ParsedDatum parsedDatum = parser.parse(fetchedDatum); // Now take the resulting HTML, process it using Dom4J SAXReader reader = new SAXReader(new Parser()); reader.setEncoding("UTF-8"); String htmlWithMarkup = parsedDatum.getParsedText(); Document doc = reader.read(new StringInputStream(htmlWithMarkup)); // We have to do helicopter stunts since HTML has a global namespace on it, set // at the <html> element level. XPath xpath = DocumentHelper.createXPath("/xhtml:html/xhtml:body/xhtml:p"); Map<String, String> namespaceUris = new HashMap<String, String>(); namespaceUris.put("xhtml", "http://www.w3.org/1999/xhtml"); xpath.setNamespaceURIs(namespaceUris); Node paragraphNode = xpath.selectSingleNode(doc); Assert.assertNotNull(paragraphNode); Assert.assertEquals("this is a test", paragraphNode.getText()); }
/** * Unregisters all JSP page servlets for a plugin. * * @param webXML the web.xml file containing JSP page names to servlet class file mappings. */ public static void unregisterServlets(File webXML) { if (!webXML.exists()) { Log.error( "Could not unregister plugin servlets, file " + webXML.getAbsolutePath() + " does not exist."); return; } // Find the name of the plugin directory given that the webXML file // lives in plugins/[pluginName]/web/web.xml String pluginName = webXML.getParentFile().getParentFile().getParentFile().getName(); try { SAXReader saxReader = new SAXReader(false); saxReader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); Document doc = saxReader.read(webXML); // Find all <servelt-mapping> entries to discover name to URL mapping. List names = doc.selectNodes("//servlet-mapping"); for (int i = 0; i < names.size(); i++) { Element nameElement = (Element) names.get(i); String url = nameElement.element("url-pattern").getTextTrim(); // Destroy the servlet than remove from servlets map. GenericServlet servlet = servlets.get(pluginName + url); if (servlet != null) { servlet.destroy(); } servlets.remove(pluginName + url); servlet = null; } } catch (Throwable e) { Log.error(e.getMessage(), e); } }
/** * 获取某一节点的文本内容; * * @param inputxml xml文件; * @param XPath * @return */ @SuppressWarnings("unchecked") public String[] getNodeTextValue(File inputxml, String XPath) { String nodeTextValue = ""; // 储存节点属性值; if (XPath.indexOf("@") >= 0) { return null; } SAXReader saxReader = new SAXReader(); Document document = null; try { document = saxReader.read(inputxml); List list = document.selectNodes(XPath); Node n = document.selectSingleNode(XPath); n.getStringValue(); Iterator it = list.iterator(); while (it.hasNext()) { Element text = (Element) it.next(); nodeTextValue += text.getText() + ","; } } catch (Exception e) { e.printStackTrace(); } if (nodeTextValue.length() > 0) { nodeTextValue = nodeTextValue.substring(0, nodeTextValue.length() - 1); } return nodeTextValue.split(","); }