Java Code Examples for org.dom4j.Document

The following are top voted examples for showing how to use org.dom4j.Document. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: tulingchat   File: MessageUtil.java   View source code 7 votes vote down vote up
/**
 * @param @param request
 * @param @throws Exception
 * @Description: 解析微信发来的请求(XML)
 */
@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;
}
 
Example 2
Project: iunet-blog   File: IndexController.java   View source code 6 votes vote down vote up
/**
 * 验证是否具有子功能权限
 * 
 * @param ds
 * @param parentId
 * @return
 */
private boolean hadSubItemRight(Document ds, int parentId)
{
	List<Element> elments = ds.getRootElement().selectNodes("function[id!=0 and parentId=" + parentId + "]");
	String strId = null;

	for (Element item : elments)
	{
		strId = item.selectSingleNode("id").getText();

		if (item.selectSingleNode("flag").getText().equals("1") || hadSubItemRight(ds, Integer.parseInt(strId)))
		{
			return true;
		}
	}
	return false;
}
 
Example 3
Project: k-framework   File: AlipaySubmit.java   View source code 6 votes vote down vote up
/**
    * 用于防钓鱼,调用接口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();
   }
 
Example 4
Project: wasexport   File: XmlConverUtil.java   View source code 6 votes vote down vote up
@SuppressWarnings("unchecked")
public static Map<String, Object> Dom2Map(Document doc) {
	Map<String, Object> map = new HashMap<String, Object>();
	if (doc == null)
		return map;
	Element root = doc.getRootElement();
	for (Iterator iterator = root.elementIterator(); iterator.hasNext();) {
		Element e = (Element) iterator.next();
		List list = e.elements();
		if (list.size() > 0) {
			map.put(e.getName(), Dom2Map(e));
		} else
			map.put(e.getName(), e.getText());
	}
	return map;
}
 
Example 5
Project: atlas   File: ManifestFileUtils.java   View source code 6 votes vote down vote up
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;
}
 
Example 6
Project: bdf2   File: NexusAddonParser.java   View source code 6 votes vote down vote up
@SuppressWarnings("rawtypes")
public Map<String, Object> parseAddonInfoLastSnapshotVersionMetaData(String xml) throws Exception {
	InputStream inputStream = toInputStream(xml);
	try {
		Document document = saxReader.read(inputStream);
		List list = document.selectNodes("//metadata/versioning/snapshot");
		Iterator iter = list.iterator();
		while (iter.hasNext()) {
			Element element = (Element) iter.next();
			Map<String, Object> map = new HashMap<String, Object>();
			for (Iterator iterInner = element.elementIterator(); iterInner.hasNext();) {
				Element elementInner = (Element) iterInner.next();
				map.put(elementInner.getName(), elementInner.getText());
			}
			return map;
		}
	} finally {
		inputStream.close();
	}
	return null;
}
 
Example 7
Project: iBase4J-Common   File: XmlUtil.java   View source code 6 votes vote down vote up
/**
 * 解析XML并将其节点元素压入Dto返回(基于节点值形式的XML格式)
 * 
 * @param pStrXml 待解析的XML字符串
 * @param pXPath 节点路径(例如:"//paralist/row" 则表示根节点paralist下的row节点的xPath路径)
 * @return outDto 返回Dto
 */
public static final Map parseXml2Map(String pStrXml, String pXPath) {
    Map map = new HashMap();
    String strTitle = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
    Document document = null;
    try {
        if (pStrXml.indexOf("<?xml") < 0) pStrXml = strTitle + pStrXml;
        document = DocumentHelper.parseText(pStrXml);
    } catch (DocumentException e) {
        logger.error("==开发人员请注意:==\n将XML格式的字符串转换为XML DOM对象时发生错误啦!" + "\n详细错误信息如下:", e);
    }
    // 获取根节点
    Element elNode = document.getRootElement();
    // 遍历节点属性值将其压入Dto
    for (Iterator it = elNode.elementIterator(); it.hasNext();) {
        Element leaf = (Element)it.next();
        map.put(leaf.getName().toLowerCase(), leaf.getData());
    }
    return map;
}
 
Example 8
Project: iBase4J-Common   File: XmlUtil.java   View source code 6 votes vote down vote up
/**
 * 将Dto转换为符合XML标准规范格式的字符串(基于属性值形式)
 * 
 * @param map 传入的Dto对象
 * @param pRootNodeName 根节点名
 * @param pFirstNodeName 一级节点名
 * @return string 返回XML格式字符串
 */
public static final String parseMap2Xml(Map map, String pRootNodeName, String pFirstNodeName) {
    Document document = DocumentHelper.createDocument();
    // 增加一个根元素节点
    document.addElement(pRootNodeName);
    Element root = document.getRootElement();
    root.addElement(pFirstNodeName);
    Element firstEl = (Element)document.selectSingleNode("/" + pRootNodeName + "/" + pFirstNodeName);
    Iterator keyIterator = map.keySet().iterator();
    while (keyIterator.hasNext()) {
        String key = (String)keyIterator.next();
        String value = (String)map.get(key);
        firstEl.addAttribute(key, value);
    }
    // 将XML的头声明信息丢去
    String outXml = document.asXML().substring(39);
    return outXml;
}
 
Example 9
Project: iBase4J-Common   File: XmlUtil.java   View source code 6 votes vote down vote up
/**
 * 将List数据类型转换为符合XML格式规范的字符串(基于节点属性值的方式)
 * 
 * @param pList 传入的List数据(List对象可以是Dto、VO、Domain的属性集)
 * @param pRootNodeName 根节点名称
 * @param pFirstNodeName 行节点名称
 * @return string 返回XML格式字符串
 */
public static final String parseList2Xml(List pList, String pRootNodeName, String pFirstNodeName) {
    Document document = DocumentHelper.createDocument();
    Element elRoot = document.addElement(pRootNodeName);
    for (int i = 0; i < pList.size(); i++) {
        Map map = (Map)pList.get(i);
        Element elRow = elRoot.addElement(pFirstNodeName);
        Iterator it = map.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry)it.next();
            elRow.addAttribute((String)entry.getKey(), String.valueOf(entry.getValue()));
        }
    }
    String outXml = document.asXML().substring(39);
    return outXml;
}
 
Example 10
Project: unitimes   File: BlobRoomAvailabilityService.java   View source code 6 votes vote down vote up
protected void sendRequest(Document request) throws IOException {
    try {
        StringWriter writer = new StringWriter();
        (new XMLWriter(writer,OutputFormat.createPrettyPrint())).write(request);
        writer.flush(); writer.close();
        SessionImplementor session = (SessionImplementor)new _RootDAO().getSession();
        Connection connection = session.getJdbcConnectionAccess().obtainConnection();
        try {
            CallableStatement call = connection.prepareCall(iRequestSql);
            call.setString(1, writer.getBuffer().toString());
            call.execute();
            call.close();
        } finally {
        	session.getJdbcConnectionAccess().releaseConnection(connection);
        }
    } catch (Exception e) {
        sLog.error("Unable to send request: "+e.getMessage(),e);
    } finally {
        _RootDAO.closeCurrentThreadSessions();
    }
}
 
Example 11
Project: wechat-api-java   File: MessageUtil.java   View source code 6 votes vote down vote up
/**
 * 解析微信发来的请求(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;
}
 
Example 12
Project: iBase4J   File: XmlUtil.java   View source code 6 votes vote down vote up
/**
 * 将mq查询结果包装成list--dto的形式,dto内容为item中的内容
 * 
 * @param recv
 * @return
 */
public static Map MqResToDto(String recv) {
	// System.out.println("####recv"+recv);
	List res = new ArrayList();
	Map map = new HashMap();
	try {
		Document doc = DocumentHelper.parseText(recv);
		List list = doc.selectNodes("//item");
		Iterator<DefaultElement> it = list.iterator();
		while (it.hasNext()) {
			Map elementdto = XmlUtil.Dom2Map(it.next());
			res.add(elementdto);
		}
		map.put("resultList", res);// 放入结果集
		/*
		 * 如果存在REC_MNT,说明是分页查询类,需要将总记录数返回
		 */
		Node de = doc.selectSingleNode("//REC_MNT");
		if (DataUtil.isNotEmpty(de)) {
			map.put("countInteger", de.getText());
		}
	} catch (Exception e) {
		log.error(XmlUtil.class, e);
	}
	return map;
}
 
Example 13
Project: automat   File: XmlUtil.java   View source code 6 votes vote down vote up
/**
 * 解析XML并将其节点元素压入Dto返回(基于节点值形式的XML格式) 应用于复杂对象
 * 
 * @param pStrXml 待解析的XML字符串
 * @return outDto 返回Dto
 */

public static Map Dom2Map(Document doc) {
	Map map = new HashMap();
	if (doc == null)
		return map;
	Element root = doc.getRootElement();
	for (Iterator iterator = root.elementIterator(); iterator.hasNext();) {
		Element e = (Element) iterator.next();
		// System.out.println(e.getName());
		List list = e.elements();
		if (list.size() > 0) {
			map.put(e.getName(), Dom2Map(e));
		} else
			map.put(e.getName(), e.getText());
	}
	return map;
}
 
Example 14
Project: automat   File: XmlUtil.java   View source code 6 votes vote down vote up
/**
 * 将Dto转换为符合XML标准规范格式的字符串(基于节点值形式)
 * 
 * @param dto 传入的Dto对象
 * @param pRootNodeName 根结点名
 * @return string 返回XML格式字符串
 */
public static final String parseDto2Xml(Map map, String pRootNodeName) {
	Document document = DocumentHelper.createDocument();
	// 增加一个根元素节点
	document.addElement(pRootNodeName);
	Element root = document.getRootElement();
	Iterator keyIterator = map.keySet().iterator();
	while (keyIterator.hasNext()) {
		String key = (String) keyIterator.next();
		String value = (String) map.get(key);
		Element leaf = root.addElement(key);
		leaf.setText(value);
	}
	// 将XML的头声明信息截去
	String outXml = document.asXML().substring(39);
	return outXml;
}
 
Example 15
Project: lams   File: Configuration.java   View source code 6 votes vote down vote up
/**
 * Parse a dom4j document conforming to the Hibernate Configuration DTD (<tt>hibernate-configuration-3.0.dtd</tt>)
 * and use its information to configure this {@link Configuration}'s state
 *
 * @param doc The dom4j document
 *
 * @return this for method chaining
 *
 * @throws HibernateException Indicates a problem performing the configuration task
 */
protected Configuration doConfigure(Document doc) throws HibernateException {
	Element sfNode = doc.getRootElement().element( "session-factory" );
	String name = sfNode.attributeValue( "name" );
	if ( name != null ) {
		properties.setProperty( Environment.SESSION_FACTORY_NAME, name );
	}
	addProperties( sfNode );
	parseSessionFactory( sfNode, name );

	Element secNode = doc.getRootElement().element( "security" );
	if ( secNode != null ) {
		parseSecurity( secNode );
	}

	LOG.configuredSessionFactory( name );
	LOG.debugf( "Properties: %s", properties );

	return this;
}
 
Example 16
Project: unitimes   File: PageAccessFilter.java   View source code 6 votes vote down vote up
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"));
	}
}
 
Example 17
Project: JAVA-   File: XmlUtil.java   View source code 6 votes vote down vote up
/**
 * 将mq查询结果包装成list--dto的形式,dto内容为item中的内容
 * 
 * @param recv
 * @return
 */
public static Map MqResToDto(String recv) {
	// System.out.println("####recv"+recv);
	List res = new ArrayList();
	Map map = new HashMap();
	try {
		Document doc = DocumentHelper.parseText(recv);
		List list = doc.selectNodes("//item");
		Iterator<DefaultElement> it = list.iterator();
		while (it.hasNext()) {
			Map elementdto = XmlUtil.Dom2Map(it.next());
			res.add(elementdto);
		}
		map.put("resultList", res);// 放入结果集
		/*
		 * 如果存在REC_MNT,说明是分页查询类,需要将总记录数返回
		 */
		Node de = doc.selectSingleNode("//REC_MNT");
		if (DataUtil.isNotEmpty(de)) {
			map.put("countInteger", de.getText());
		}
	} catch (Exception e) {
		log.error(XmlUtil.class, e);
	}
	return map;
}
 
Example 18
Project: PackagePlugin   File: FileUtil.java   View source code 6 votes vote down vote up
/**
 * 删除配置
 *
 * @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();
    }
}
 
Example 19
Project: joai-project   File: RepositoryAdminForm.java   View source code 6 votes vote down vote up
/**
 *  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;
}
 
Example 20
Project: joai-project   File: WebServiceClient.java   View source code 6 votes vote down vote up
public Document doSearch (String queryStr)
	throws WebServiceClientException {
	String verb = "Search";
	String encodedQueryStr = "";
	try {
		encodedQueryStr = URLEncoder.encode(queryStr, "UTF-8");
	} catch (Exception e) {
		String errorMsg = "WebServiceClient.urlCheck failed to encode: " + queryStr;
		throw new WebServiceClientException(errorMsg);
	}
	setRequestUrl(verb, queryStr);
	prtln ("about to sumbit request: " + getRequestUrl());
	Document doc = getResponseDoc();
	// prtln(Dom4jUtils.prettyPrint(doc));
	return doc;
}
 
Example 21
Project: etagate   File: GateSetting.java   View source code 6 votes vote down vote up
public void parse(URL is) {
		SAXReader saxReader = new SAXReader();

		try {
			Document document = saxReader.read(is);
			Element root = document.getRootElement();
			
			collectProperty(root);
			parseAuth(root);
			parseApp(root);
//			
//			System.out.println("====================parse ok=============");
//			System.out.println(properties.toString());
//			System.out.println(authSetting.toString());
		} catch (DocumentException e) {
			log.error("Load route.xml error.");
			e.printStackTrace();
		}

	}
 
Example 22
Project: iBase4J   File: XmlUtil.java   View source code 6 votes vote down vote up
/**
 * 解析XML并将其节点元素压入Dto返回(基于节点值形式的XML格式)
 * 
 * @param pStrXml 待解析的XML字符串
 * @return outDto 返回Dto
 */
public static final Map parseXml2Map(String pStrXml) {
	Map map = new HashMap();
	String strTitle = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
	Document document = null;
	try {
		if (pStrXml.indexOf("<?xml") < 0)
			pStrXml = strTitle + pStrXml;
		document = DocumentHelper.parseText(pStrXml);

	} catch (DocumentException e) {
		log.error("==开发人员请注意:==\n将XML格式的字符串转换为XML DOM对象时发生错误啦!" + "\n详细错误信息如下:", e);
	}
	// 获取根节点
	Element elNode = document.getRootElement();
	// 遍历节点属性值将其压入Dto
	for (Iterator it = elNode.elementIterator(); it.hasNext();) {
		Element leaf = (Element) it.next();
		map.put(leaf.getName().toLowerCase(), leaf.getData());
	}
	return map;
}
 
Example 23
Project: jspider   File: XmlParser.java   View source code 5 votes vote down vote up
public Document parseDocument(String xml) {
    Document document = null;
    try {
        document = DocumentHelper.parseText(xml);
    } catch (DocumentException e) {
        throw new IllegalArgumentException(e);
    }
    return document;
}
 
Example 24
Project: joai-project   File: Dom4jUtils.java   View source code 5 votes vote down vote up
/**
 *  Insert nameSpaceInformation into the root element
 *
 * @param  doc              Description of the Parameter
 * @param  rootElementName  Description of the Parameter
 * @param  nameSpaceInfo    Description of the Parameter
 * @return                  Description of the Return Value
 */
public static Document delocalizeXml(Document doc, String rootElementName, String nameSpaceInfo) {
	Element root = doc.getRootElement();
	String rootName = root.getName();
	String namespaceXml = delocalizeDocStr(doc.asXML(), rootElementName, nameSpaceInfo);
	try {
		return getXmlDocument(namespaceXml);
	} catch (Exception e) {
		prtln("unable to delocalizeItemRecordDoc(): " + e);
	}
	return null;
}
 
Example 25
Project: fcrepo3-security-jaas   File: DrupalMultisiteAuthModule.java   View source code 5 votes vote down vote up
/**
 * Parse connection entries out of the given document.
 * @param doc
 */

protected void parseConfig(Document doc) {
    config.clear();
    @SuppressWarnings("unchecked")
    List<Element> list = doc.selectNodes("//FilterDrupal_Connection/connection[@key]");
    for (Element el : list) {
        config.put(el.attributeValue("key").trim(), parseConnectionElement(el));
    }
}
 
Example 26
Project: phoenix.webui.framework   File: XmlDataSource.java   View source code 5 votes vote down vote up
/**
 * 解析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);
}
 
Example 27
Project: ARCLib   File: XmlBuilderTest.java   View source code 5 votes vote down vote up
@Test
public void addChildNodeTest() throws IOException, SAXException, TransformerException {
    Document doc = DocumentHelper.createDocument(DocumentHelper.createElement("root"));

    xmlBuilder.addNode(doc, "/root/child", "test value", uris.get("ARCLIB"));
    assertThat(doc.asXML(), is("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<root><child xmlns=\"http://arclib.lib.cas.cz/ARCLIB_XML\">test value</child></root>"));
}
 
Example 28
Project: joai-project   File: Dom4jUtils.java   View source code 5 votes vote down vote up
/**
 *  Remove nameSpaceInformation from the root element (as well as any attributes!) to facilitate xpath access
 *
 * @param  doc              Description of the Parameter
 * @param  rootElementName  Description of the Parameter
 * @return                  Description of the Return Value
 */
public static Document localizeXml(Document doc, String rootElementName) {
	String localizedXml = localizeXml(doc.asXML(), rootElementName);
	try {
		return getXmlDocument(localizedXml);
	} catch (Exception e) {
		prtln("unable to localizeItemRecord(): " + e);
	}
	return null;
}
 
Example 29
Project: voyage   File: ClientConfig.java   View source code 5 votes vote down vote up
private Element getRoot() {
	Document doc = getDocument();
	List<Element> list = doc.selectNodes("//application");
	if (list.size() > 0) {
		Element aroot = list.get(0);
		return aroot;
	}
	return null;
}
 
Example 30
Project: lams   File: Dom4JDriver.java   View source code 5 votes vote down vote up
/**
 * @since 1.4
 */
@Override
public HierarchicalStreamReader createReader(final URL in) {
    try {
        final SAXReader reader = new SAXReader();
        final Document document = reader.read(in);
        return new Dom4JReader(document, getNameCoder());
    } catch (final DocumentException e) {
        throw new StreamException(e);
    }
}
 
Example 31
Project: iBase4J   File: XmlUtil.java   View source code 5 votes vote down vote up
/**
 * 将XML规范的字符串转为List对象(XML基于节点属性值的方式)
 * 
 * @param pStrXml 传入的符合XML格式规范的字符串
 * @return list 返回List对象
 */
public static final List parseXml2List(String pStrXml) {
	List lst = new ArrayList();
	String strTitle = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
	Document document = null;
	try {
		if (pStrXml.indexOf("<?xml") < 0)
			pStrXml = strTitle + pStrXml;
		document = DocumentHelper.parseText(pStrXml);
	} catch (DocumentException e) {
		log.error("==开发人员请注意:==\n将XML格式的字符串转换为XML DOM对象时发生错误啦!" + "\n详细错误信息如下:", e);
	}
	// 获取到根节点
	Element elRoot = document.getRootElement();
	// 获取根节点的所有子节点元素
	Iterator elIt = elRoot.elementIterator();
	while (elIt.hasNext()) {
		Element el = (Element) elIt.next();
		Iterator attrIt = el.attributeIterator();
		Map map = new HashMap();
		while (attrIt.hasNext()) {
			Attribute attribute = (Attribute) attrIt.next();
			map.put(attribute.getName().toLowerCase(), attribute.getData());
		}
		lst.add(map);
	}
	return lst;
}
 
Example 32
Project: ExcelUtils   File: ParseXMLUtilTest.java   View source code 5 votes vote down vote up
@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();

    }
 
Example 33
Project: joai-project   File: ElementsOrderer.java   View source code 5 votes vote down vote up
static void conceptTest() throws Exception {
	String xmlPath = "C:/tmp/concept-tester.xml";
	String xml = Files.readFile(xmlPath).toString();
	Document record = Dom4jUtils.localizeXml(Dom4jUtils.getXmlDocument(xml));
	ElementsOrderer orderer = new ElementsOrderer(record, "//contents/*/@num");
	orderer.processDoc();
	orderer = new ElementsOrderer(record, "//hierarchy/*/@num");
	orderer.processDoc();
	orderer = new ElementsOrderer(record, "//relations/*/@num");
	orderer.processDoc();
	prtln("\n ORDERER");
	prtln(Dom4jUtils.prettyPrint(orderer.doc));
}
 
Example 34
Project: joai-project   File: XMLQueryParser.java   View source code 5 votes vote down vote up
private static Query doGetLuceneQuery(Document xmlDoc, QueryParser queryParser) throws Exception {
	List queryElement = xmlDoc.selectNodes("/Query/*");
	if (queryElement == null || queryElement.size() == 0)
		throw new Exception("Error parsing Query: root element '<Query>' is empty or missing.");
	if (queryElement.size() > 1)
		throw new Exception("Error parsing Query: '<Query>' may contain only 1 child element but " + queryElement.size() + " were found.");

	return getLuceneQuery((Element) queryElement.get(0), queryParser);
}
 
Example 35
Project: urule   File: RepositoryServiceImpl.java   View source code 5 votes vote down vote up
@Override
public List<UserPermission> loadResourceSecurityConfigs(String companyId) throws Exception{
	List<UserPermission> configs=new ArrayList<UserPermission>();
	String filePath=RESOURCE_SECURITY_CONFIG_FILE+(companyId == null ? "" : companyId);
	Node rootNode=getRootNode();
	Node fileNode = rootNode.getNode(filePath);
	Property property = fileNode.getProperty(DATA);
	Binary fileBinary = property.getBinary();
	InputStream inputStream = fileBinary.getStream();
	String content = IOUtils.toString(inputStream, "utf-8");
	inputStream.close();
	Document document = DocumentHelper.parseText(content);
	Element rootElement = document.getRootElement();
	for (Object obj : rootElement.elements()) {
		if (!(obj instanceof Element)) {
			continue;
		}
		Element element = (Element) obj;
		if (!element.getName().equals("user-permission")) {
			continue;
		}
		UserPermission userResource=new UserPermission();
		userResource.setUsername(element.attributeValue("username"));
		userResource.setProjectConfigs(parseProjectConfigs(element));
		configs.add(userResource);
	}
	return configs;
}
 
Example 36
Project: unitimes   File: ImportXmlFile.java   View source code 5 votes vote down vote up
public static void main(String[] args) {
try {
	// Configure logging
       org.apache.log4j.PropertyConfigurator.configure(ApplicationProperties.getProperties());
       
       // Configure hibernate
       HibernateUtil.configureHibernate(ApplicationProperties.getProperties());
       
       // Load an XML file
       Document document = (new SAXReader()).read(new File(args[0]));
       
       // External id of the manager doing the import (can be null)
       String managerId = (args.length >= 2 ? args[1] : null);
       
       // Log writer to print messages from the import (can be null)
       DataExchangeHelper.LogWriter logger = new DataExchangeHelper.LogWriter() {
       	@Override
       	public void println(String message) {
       		Logger.getLogger(ImportXmlFile.class).info(message);
       	}
       };
       
       // Import document
       DataExchangeHelper.importDocument(document, managerId, logger);
       
       // Close hibernate
       HibernateUtil.closeHibernate();
} catch (Exception e) {
	Logger.getLogger(ImportXmlFile.class).error("Error: " +e.getMessage(), e);
}
  }
 
Example 37
Project: urule   File: AbstractReferenceUpdater.java   View source code 5 votes vote down vote up
protected String xmlToString(Document doc){
	StringWriter stringWriter = new StringWriter();
	OutputFormat xmlFormat = new OutputFormat();
	xmlFormat.setEncoding("UTF-8");
	XMLWriter xmlWriter = new XMLWriter(stringWriter, xmlFormat);
	try {
		xmlWriter.write(doc);
		xmlWriter.close();
		return stringWriter.toString();
	} catch (IOException e) {
		e.printStackTrace();
		throw new RuleException(e);
	}
}
 
Example 38
Project: joai-project   File: EnsureMinimalDocument.java   View source code 5 votes vote down vote up
/**
 *  Constructor for the EnsureMinimalDocument object
 *
 *@param  doc           instanceDocument
 *@param  schemaHelper  the schemaHelper for doc's framework
 */
private EnsureMinimalDocument(Document doc, SchemaHelper schemaHelper) {
	this.schemaHelper = schemaHelper;
	this.minimalDoc = this.schemaHelper.getMinimalDocument();
	prtln("----------------");
	prtln("Minimal Doc **\n" + Dom4jUtils.prettyPrint(this.minimalDoc));
	prtln("----------------");
	this.doc = doc;
	this.docMap = new DocMap(doc, schemaHelper);
}
 
Example 39
Project: EasyML   File: OozieGraphXMLParser.java   View source code 5 votes vote down vote up
/**
 * @param xml xml description
 * @throws DocumentException 
 */
public static OozieGraph parse(String xml) throws DocumentException {
	OozieGraph graph = new OozieGraph();
	Document doc =DocumentHelper.parseText(xml);
	Element root = doc.getRootElement();
	// parse widgets
	List<Element> nodes = root.elements("widget");
	for( Element node: nodes){
		String type = node.attributeValue("type");
		if (type.equals("dataset")) {
			OozieDatasetNode odn = parseDatasetNode(node);
			graph.addDatasetNode(odn);
		} else if(type.equals("program")){
			OozieProgramNode opn = parseProgramNode(node);
			graph.addProgramNode(opn);
			graph.addActiveNode(opn.getId());
		}

	}

	// parse edges
	List<Element> enodes = root.elements("edge");
	for(Element elem: enodes){
		OozieEdge edge = parseOozieEdge( elem);
		if (edge != null)
			graph.addEdge(edge);
	}

	return graph;
}
 
Example 40
Project: urule   File: ScriptDecisionTableReferenceUpdater.java   View source code 5 votes vote down vote up
public String update(String oldPath, String newPath, String xml) {
	try{
		boolean modify=false;
		Document doc=DocumentHelper.parseText(xml);
		Element element=doc.getRootElement();
		for(Object obj:element.elements()){
			if(!(obj instanceof Element)){
				continue;
			}
			Element ele=(Element)obj;
			String name=ele.getName();
			boolean match=false;
			if(name.equals("import-variable-library")){
				match=true;
			}else if(name.equals("import-constant-library")){
				match=true;
			}else if(name.equals("import-action-library")){
				match=true;
			}else if(name.equals("import-parameter-library")){
				match=true;
			}
			if(!match){
				continue;
			}
			String path=ele.attributeValue("path");
			if(path.endsWith(oldPath)){
				ele.addAttribute("path", newPath);
				modify=true;
			}
		}
		if(modify){
			return xmlToString(doc);
		}
		return null;
	}catch(Exception ex){
		throw new RuleException(ex);
	}
}