下面列出了java.beans.PropertyEditorSupport#org.dom4j.io.SAXReader 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static Document getDocument(Reader reader) throws DocumentException, IOException {
SAXReader saxReader = new SAXReader();
Document document = null;
try {
document = saxReader.read(reader);
} catch (DocumentException e) {
throw e;
} finally {
if (reader != null) {
reader.close();
}
}
return document;
}
/**
* 解析xml
*/
@SuppressWarnings("unchecked")
public static Map<String, String> parseXml(InputStream inputStream) throws Exception {
Map<String, String> map = Maps.newHashMap();
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();
return map;
}
/**
* 用于防钓鱼,调用接口query_timestamp来获取时间戳的处理函数
* 注意:远程解析XML出错,与服务器是否支持SSL等配置有关
* @return 时间戳字符串
* @throws Exception
* @throws UnsupportedEncodingException
* @throws IOException
* @throws DocumentException
* @throws MalformedURLException
*/
public static Map<String,String> parseRespose(String reponse) throws Exception {
Map<String,String> respMap = new HashMap<String,String>();
try {
SAXReader reader = new SAXReader();
Document doc = reader.read(new ByteArrayInputStream(reponse.getBytes("GBK")));
Node isSuccessNode = doc.selectSingleNode("//alipay/is_success");
if (isSuccessNode.getText().equals("T")) {
// 判断是否有成功标示
Node tradeStatusNode = doc.selectSingleNode("//response/trade/trade_status");
respMap.put("trade_status", tradeStatusNode.getText());
}
respMap.put("is_success", isSuccessNode.getText());
} catch (Exception e) {
LOG.error(e.getMessage(),reponse);
}
return respMap;
}
@Test
public void collectionOfPetsAsStringNotSelected() throws Exception {
this.tag.setPath("pets");
this.tag.setValue("Santa's Little Helper");
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 checkboxElement = (Element) document.getRootElement().elements().get(0);
assertEquals("input", checkboxElement.getName());
assertEquals("checkbox", checkboxElement.attribute("type").getValue());
assertEquals("pets", checkboxElement.attribute("name").getValue());
assertNull(checkboxElement.attribute("checked"));
}
@Test
public void withSingleValueNull() throws Exception {
this.bean.setName(null);
this.tag.setPath("name");
this.tag.setValue("Rob Harrop");
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 checkboxElement = (Element) document.getRootElement().elements().get(0);
assertEquals("input", checkboxElement.getName());
assertEquals("checkbox", checkboxElement.attribute("type").getValue());
assertEquals("name", checkboxElement.attribute("name").getValue());
assertNull(checkboxElement.attribute("checked"));
assertEquals("Rob Harrop", checkboxElement.attribute("value").getValue());
}
/**
* Returns the value of an element selected via an xpath expression from
* a component's component.xml file.
*
* @param component the component.
* @param xpath the xpath expression.
* @return the value of the element selected by the xpath expression.
*/
private String getElementValue(Component component, String xpath) {
File componentDir = componentDirs.get(component);
if (componentDir == null) {
return null;
}
try {
File componentConfig = new File(componentDir, "component.xml");
if (componentConfig.exists()) {
SAXReader saxReader = new SAXReader();
Document componentXML = saxReader.read(componentConfig);
Element element = (Element)componentXML.selectSingleNode(xpath);
if (element != null) {
return element.getTextTrim();
}
}
}
catch (Exception e) {
manager.getLog().error(e);
}
return null;
}
@Test
public void withSingleValueBooleanObjectChecked() throws Exception {
this.tag.setPath("someBoolean");
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 not rendered", 2, rootElement.elements().size());
Element checkboxElement = (Element) rootElement.elements().get(0);
assertEquals("input", checkboxElement.getName());
assertEquals("checkbox", checkboxElement.attribute("type").getValue());
assertEquals("someBoolean1", checkboxElement.attribute("id").getValue());
assertEquals("someBoolean", checkboxElement.attribute("name").getValue());
assertEquals("checked", checkboxElement.attribute("checked").getValue());
assertEquals("true", checkboxElement.attribute("value").getValue());
}
@Test
public void collectionOfPets() throws Exception {
this.tag.setPath("pets");
this.tag.setValue(new Pet("Rudiger"));
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 checkboxElement = (Element) document.getRootElement().elements().get(0);
assertEquals("input", checkboxElement.getName());
assertEquals("checkbox", checkboxElement.attribute("type").getValue());
assertEquals("pets", checkboxElement.attribute("name").getValue());
assertEquals("Rudiger", checkboxElement.attribute("value").getValue());
assertEquals("checked", checkboxElement.attribute("checked").getValue());
}
@Test
public void collectionOfPetsAsStringNotSelected() throws Exception {
this.tag.setPath("pets");
this.tag.setValue("Santa's Little Helper");
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 checkboxElement = (Element) document.getRootElement().elements().get(0);
assertEquals("input", checkboxElement.getName());
assertEquals("checkbox", checkboxElement.attribute("type").getValue());
assertEquals("pets", checkboxElement.attribute("name").getValue());
assertNull(checkboxElement.attribute("checked"));
}
@Test
public void withoutItems() throws Exception {
this.tag.setItemValue("isoCode");
this.tag.setItemLabel("name");
this.selectTag.setPath("testBean");
this.selectTag.doStartTag();
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
this.tag.doEndTag();
this.selectTag.doEndTag();
String output = getOutput();
SAXReader reader = new SAXReader();
Document document = reader.read(new StringReader(output));
Element rootElement = document.getRootElement();
List children = rootElement.elements();
assertEquals("Incorrect number of children", 0, children.size());
}
private static Document creXmlDoc(String xmlStr) {
if (Strings.empty(xmlStr)) {
throw new RuntimeException("参数不能为空");
}
SAXReader saxReader = new SAXReader();
Document document = null;
try {
document = saxReader.read(new ByteArrayInputStream(xmlStr.getBytes("UTF-8")));
Element rootElement = document.getRootElement();
String getXMLEncoding = document.getXMLEncoding();
String rootname = rootElement.getName();
System.out.println("getXMLEncoding>>>" + getXMLEncoding + ",rootname>>>" + rootname);
OutputFormat format = OutputFormat.createPrettyPrint();
/** 指定XML字符集编码 */
format.setEncoding("UTF-8");
Logger.info(xmlStr);
} catch (Exception e) {
e.printStackTrace();
}
return document;
}
/**
* timeLength, fileSize, urls
*
* @param epReqApi
* @throws IOException
* @throws DocumentException
*/
private void parseEpApiResponse(String epReqApi) throws IOException, DocumentException {
String response = HttpUtil.getResponseContent(epReqApi);
SAXReader reader = new SAXReader();
org.dom4j.Element rootElement = reader.read(new ByteArrayInputStream(response.getBytes("utf-8"))).getRootElement();
timeLength = Integer.parseInt(rootElement.element("timelength").getText().trim());
List<org.dom4j.Element> elements = rootElement.elements("durl");
for (org.dom4j.Element ele : elements) {
int curSize = Integer.parseInt(ele.element("size").getText());
fileSize += curSize;
String url = ele.element("url").getText();
urls.add(url);
}
println(fileName + ": " + fileSize / 1024 / 1024 + "M");
}
@Test
public void withoutItemsEnumBindTarget() throws Exception {
BeanWithEnum testBean = new BeanWithEnum();
testBean.setTestEnum(TestEnum.VALUE_2);
getPageContext().getRequest().setAttribute("testBean", testBean);
this.tag.setPath("testEnum");
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
String output = "<div>" + getOutput() + "</div>";
SAXReader reader = new SAXReader();
Document document = reader.read(new StringReader(output));
Element rootElement = document.getRootElement();
assertEquals(2, rootElement.elements().size());
Node value1 = rootElement.selectSingleNode("//input[@value = 'VALUE_1']");
Node value2 = rootElement.selectSingleNode("//input[@value = 'VALUE_2']");
assertEquals("TestEnum: VALUE_1", rootElement.selectSingleNode("//label[@for = '" + value1.valueOf("@id") + "']").getText());
assertEquals("TestEnum: VALUE_2", rootElement.selectSingleNode("//label[@for = '" + value2.valueOf("@id") + "']").getText());
assertEquals(value2, rootElement.selectSingleNode("//input[@checked]"));
}
@Test
public void withoutItemsEnumBindTargetWithExplicitLabelsAndValues() throws Exception {
BeanWithEnum testBean = new BeanWithEnum();
testBean.setTestEnum(TestEnum.VALUE_2);
getPageContext().getRequest().setAttribute("testBean", testBean);
this.tag.setPath("testEnum");
this.tag.setItemLabel("enumLabel");
this.tag.setItemValue("enumValue");
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
String output = "<div>" + getOutput() + "</div>";
SAXReader reader = new SAXReader();
Document document = reader.read(new StringReader(output));
Element rootElement = document.getRootElement();
assertEquals(2, rootElement.elements().size());
Node value1 = rootElement.selectSingleNode("//input[@value = 'Value: VALUE_1']");
Node value2 = rootElement.selectSingleNode("//input[@value = 'Value: VALUE_2']");
assertEquals("Label: VALUE_1", rootElement.selectSingleNode("//label[@for = '" + value1.valueOf("@id") + "']").getText());
assertEquals("Label: VALUE_2", rootElement.selectSingleNode("//label[@for = '" + value2.valueOf("@id") + "']").getText());
assertEquals(value2, rootElement.selectSingleNode("//input[@checked]"));
}
@Test
public void hiddenElementOmittedOnDisabled() 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 radioButtonElement = (Element) spanElement.elements().get(0);
assertEquals("input", radioButtonElement.getName());
assertEquals("radio", radioButtonElement.attribute("type").getValue());
assertEquals("stringArray", radioButtonElement.attribute("name").getValue());
assertEquals("checked", radioButtonElement.attribute("checked").getValue());
assertEquals("disabled", radioButtonElement.attribute("disabled").getValue());
assertEquals("foo", radioButtonElement.attribute("value").getValue());
}
@Test
public void spanElementCustomizable() throws Exception {
this.tag.setPath("stringArray");
this.tag.setItems(new Object[] {"foo", "bar", "baz"});
this.tag.setElement("element");
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 spanElement = (Element) document.getRootElement().elements().get(0);
assertEquals("element", spanElement.getName());
}
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 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 Document load(String filename) {
Document document = null;
Reader xmlReader = null;
InputStream stream = null;
try {
SAXReader saxReader = new SAXReader();
stream = getClass().getClassLoader().getResourceAsStream(filename);
xmlReader = new InputStreamReader(stream, "UTF-8");
document = saxReader.read(xmlReader);
}
catch (Exception ex) {
_logger.error(String.format("the filename of document is %s, error [%s]" , filename
,ex.getMessage()));
document = DocumentHelper.createDocument();
document.addElement("ROOT");
} finally {
closeStream(xmlReader);
closeStream(stream);
}
return document;
}
@Test
public void hiddenElementOmittedOnDisabled() 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());
}
@Test
public void multipleExplicitlyFalse() throws Exception {
this.tag.setPath("name");
this.tag.setItems(Country.getCountries());
this.tag.setItemValue("isoCode");
this.tag.setMultiple("false");
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
String output = getOutput();
output = "<doc>" + output + "</doc>";
SAXReader reader = new SAXReader();
Document document = reader.read(new StringReader(output));
Element rootElement = document.getRootElement();
assertEquals(1, rootElement.elements().size());
Element selectElement = rootElement.element("select");
assertEquals("select", selectElement.getName());
assertEquals("name", selectElement.attribute("name").getValue());
assertNull(selectElement.attribute("multiple"));
List children = selectElement.elements();
assertEquals("Incorrect number of children", 4, children.size());
}
@Test
public void collectionOfPetsAsString() throws Exception {
this.tag.setPath("pets");
this.tag.setValue("Spot");
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 checkboxElement = (Element) document.getRootElement().elements().get(0);
assertEquals("input", checkboxElement.getName());
assertEquals("checkbox", checkboxElement.attribute("type").getValue());
assertEquals("pets", checkboxElement.attribute("name").getValue());
assertEquals("checked", checkboxElement.attribute("checked").getValue());
}
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 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"));
}
}
/**
* Builds the document XML model up based the given reader of XML data.
* @param in the input stream used to build the xml document
* @throws java.io.IOException thrown when an error occurs reading the input stream.
*/
private void buildDoc(Reader in) throws IOException {
try {
SAXReader xmlReader = new SAXReader();
xmlReader.setEncoding("UTF-8");
document = xmlReader.read(in);
buildNowVersion();
}
catch (Exception e) {
Log.error("Error reading XML properties", e);
throw new IOException(e.getMessage());
}
finally {
if (in != null) {
in.close();
}
}
}
/**
* 构造函数
* @param context
* @param templatePath 模板路径
*/
public TemplateCommentGenerator(Context context, String templatePath) {
try {
Document doc = null;
File file = new File(templatePath);
if (file.exists()) {
doc = new SAXReader().read(file);
} else {
logger.error("没有找到对应注释模板:" + templatePath);
}
// 遍历comment 节点
if (doc != null) {
for (EnumNode node : EnumNode.values()) {
Element element = doc.getRootElement().elementByID(node.value());
if (element != null) {
Configuration cfg = new Configuration(Configuration.VERSION_2_3_26);
// 字符串清理
Template template = new Template(node.value(), element.getText(), cfg);
templates.put(node, template);
}
}
}
// 解析mybatis generator 注释配置
CommentGeneratorConfiguration config = context.getCommentGeneratorConfiguration();
if (config != null) {
this.addConfigurationProperties(config.getProperties());
}
} catch (Exception e) {
logger.error("注释模板XML解析失败!", e);
}
}
@SuppressWarnings("rawtypes")
private void assertHtmlOutput(String output) throws Exception {
SAXReader reader = new SAXReader();
Document document = reader.read(new StringReader(output));
List nodes = document.getRootElement().selectNodes("/html/body/table/tr");
Element tr1 = (Element) nodes.get(0);
assertRowElement(tr1, "1", "Whatsit", "12.99");
Element tr2 = (Element) nodes.get(1);
assertRowElement(tr2, "2", "Thingy", "13.99");
Element tr3 = (Element) nodes.get(2);
assertRowElement(tr3, "3", "Gizmo", "14.99");
Element tr4 = (Element) nodes.get(3);
assertRowElement(tr4, "4", "Cranktoggle", "11.99");
}
/**
* <p>
* 解析合并请求xml数据流
* </p>
*
* @param request
*/
private Document parseRequestXML(HttpServletRequest request) {
ServletInputStream is = null;
SAXReader saxReader = new SAXReader();
try {
is = request.getInputStream();
return saxReader.read(is);
} catch (Exception e) {
throw new BusinessException("解析合并请求的xml数据流失败", e);
} finally {
FileHelper.closeSteam(is, null);
}
}
@Override
public Document getRequest(Type requestType) throws IOException {
Reader reader = iRequest.getReader();
try {
return new SAXReader().read(reader);
} catch (DocumentException e) {
throw new IOException(e.getMessage(), e);
} finally {
reader.close();
}
}
public void deployViews(Reader xml) {
lock.readLock().lock();
try {
checkInitialized();
} finally {
lock.readLock().unlock();
}
SAXReader reader = new SAXReader();
Document doc;
try {
doc = reader.read(xml);
} catch (DocumentException e) {
throw new RuntimeException("Unable to read views xml", e);
}
Element rootElem = doc.getRootElement();
for (Element includeElem : Dom4j.elements(rootElem, "include")) {
String file = includeElem.attributeValue("file");
if (!StringUtils.isBlank(file))
deployViews(file);
}
for (Element viewElem : Dom4j.elements(rootElem, "view")) {
deployView(rootElem, viewElem);
}
}