Java 类org.dom4j.DocumentHelper 实例源码

项目:iBase4J-Common    文件:XmlUtil.java   
/**
 * 将Dto转换为符合XML标准规范格式的字符串(基于节点值形式)
 * 
 * @param map 传入的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;
}
项目:iBase4J-Common    文件:XmlUtil.java   
/**
 * 将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;
}
项目:iBase4J-Common    文件:XmlUtil.java   
/**
 * 将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;
}
项目:iBase4J-Common    文件:XmlUtil.java   
/**
 * 将List数据类型转换为符合XML格式规范的字符串(基于节点值的方式)
 * 
 * @param pList 传入的List数据(List对象可以是Dto、VO、Domain的属性集)
 * @param pRootNodeName 根节点名称
 * @param pFirstNodeName 行节点名称
 * @return string 返回XML格式字符串
 */
public static final String parseList2XmlBasedNode(List pList, String pRootNodeName, String pFirstNodeName) {
    Document document = DocumentHelper.createDocument();
    Element output = document.addElement(pRootNodeName);
    for (int i = 0; i < pList.size(); i++) {
        Map map = (Map)pList.get(i);
        Element elRow = output.addElement(pFirstNodeName);
        Iterator it = map.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry)it.next();
            Element leaf = elRow.addElement((String)entry.getKey());
            leaf.setText(String.valueOf(entry.getValue()));
        }
    }
    String outXml = document.asXML().substring(39);
    return outXml;
}
项目:iBase4J-Common    文件:XmlUtil.java   
/**
 * 将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) {
        logger.error("", e);
    }
    return map;
}
项目:JAVA-    文件:XmlUtil.java   
/**
 * 将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;
}
项目:unitimes    文件:StudentSectioningQueue.java   
protected static void addItem(org.hibernate.Session hibSession, UserContext user, Long sessionId, Type type, Long... ids) {
    StudentSectioningQueue q = new StudentSectioningQueue();
    q.setTimeStamp(new Date());
    q.setType(type.ordinal());
    q.setSessionId(sessionId);
    Document d = DocumentHelper.createDocument();
    Element root = d.addElement("generic");
    if (user != null) {
        Element e = root.addElement("user");
        e.addAttribute("id", user.getExternalUserId()).setText(user.getName());
    }
    if (ids != null && ids.length > 0) {
        for (Long id: ids)
            root.addElement("id").setText(id.toString());
    }
    q.setMessage(d);
    hibSession.save(q);
}
项目:automat    文件:XmlUtil.java   
/**
 * 解析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;
}
项目:automat    文件:XmlUtil.java   
/**
 * 将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;
}
项目:automat    文件:XmlUtil.java   
/**
 * 将Dto转换为符合XML标准规范格式的字符串(基于节点值形式)
 * 
 * @param dto 传入的Dto对象
 * @param pRootNodeName 根结点名
 * @return string 返回XML格式字符串
 */
public static final String parseDto2XmlHasHead(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);
    String outXml = document.asXML();
    return outXml;
}
项目:automat    文件:XmlUtil.java   
/**
 * 将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;
}
项目:automat    文件:XmlUtil.java   
/**
 * 将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;
}
项目:automat    文件:XmlUtil.java   
/**
 * 将List数据类型转换为符合XML格式规范的字符串(基于节点值的方式)
 * 
 * @param pList 传入的List数据(List对象可以是Dto、VO、Domain的属性集)
 * @param pRootNodeName 根节点名称
 * @param pFirstNodeName 行节点名称
 * @return string 返回XML格式字符串
 */
public static final String parseList2XmlBasedNode(List pList, String pRootNodeName, String pFirstNodeName) {
    Document document = DocumentHelper.createDocument();
    Element output = document.addElement(pRootNodeName);
    for (int i = 0; i < pList.size(); i++) {
        Map map = (Map) pList.get(i);
        Element elRow = output.addElement(pFirstNodeName);
        Iterator it = map.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            Element leaf = elRow.addElement((String) entry.getKey());
            leaf.setText(String.valueOf(entry.getValue()));
        }
    }
    String outXml = document.asXML().substring(39);
    return outXml;
}
项目:IPE-LWM2M    文件:SimpleLwm2mServer.java   
private void emitValue(String path, String content){

    Document document = DocumentHelper.createDocument();
    Element eleRoot = document.addElement("msg");

    Element elePath = eleRoot.addElement("path");
    Element eleContent = eleRoot.addElement("value");

    elePath.setText(path);
    eleContent.setText(content);

    String msg = document.asXML();

    if(handler != null){
        MsgReceiveEvent event = new MsgReceiveEvent(this, msg);
        handler.receiveMsgEvent(event);
    }
}
项目:xpath-to-xml    文件:XmlBuilderTest.java   
@Test
public void shouldBuildDocumentFromSetOfXPaths() throws XPathExpressionException, IOException {
    Map<String, Object> xmlProperties = fixtureAccessor.getXmlProperties();
    Document builtDocument = new XmlBuilder(namespaceContext)
            .putAll(xmlProperties.keySet())
            .build(DocumentHelper.createDocument());

    for (Entry<String, Object> xpathToValuePair : xmlProperties.entrySet()) {
        XPath xpath = builtDocument.createXPath(xpathToValuePair.getKey());
        if (null != namespaceContext) {
            xpath.setNamespaceContext(new SimpleNamespaceContextWrapper(namespaceContext));
        }
        assertThat(xpath.evaluate(builtDocument)).isNotNull();
    }
    assertThat(xmlToString(builtDocument)).isEqualTo(fixtureAccessor.getPutXml());
}
项目:JAVA-    文件:XmlUtil.java   
/**
 * 将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;
}
项目:joai-project    文件:InfoXML.java   
private Element getTagElement (String _tag, String _namespacePrefix, String _namespaceURI ) {

    Element tagElement = null; // caller is responsible for handling null

    try {
        // TODO  this isn't complete, as we can have any arbitrary tag and values for them infinitely deep
        XPath xpath = DocumentHelper.createXPath( "//" + ( _namespacePrefix != null ? _namespacePrefix + ":" : "" ) + _tag.trim() );
        SimpleNamespaceContext ns = new SimpleNamespaceContext();
        ns.addNamespace( _namespacePrefix, _namespaceURI );  
        xpath.setNamespaceContext(ns);

        tagElement = ((Element)xpath.selectSingleNode(this.infoxmlDoc));

    }  catch ( Exception e ) {
        e.printStackTrace();
    }

    return tagElement;      
}
项目:sbc-qsystem    文件:NetCommander.java   
/**
 * Получение конфигурации главного табло - ЖК или плазмы. Это XML-файл лежащий в папку
 * приложения mainboard.xml
 *
 * @param netProperty параметры соединения с сервером
 * @return корень XML-файла mainboard.xml
 * @throws DocumentException принятый текст может не преобразоваться в XML
 */
public static Element getBoardConfig(INetProperty netProperty) throws DocumentException {
    QLog.l().logger().info("Получение конфигурации главного табло - ЖК или плазмы.");
    // загрузим ответ
    final String res;
    try {
        res = send(netProperty, Uses.TASK_GET_BOARD_CONFIG, null);
    } catch (QException e) {
        throw new ClientException(Locales.locMes("bad_response") + "\n" + e.toString());
    }
    final Gson gson = GsonPool.getInstance().borrowGson();
    final RpcGetSrt rpc;
    try {
        rpc = gson.fromJson(res, RpcGetSrt.class);
    } catch (JsonSyntaxException ex) {
        throw new ClientException(Locales.locMes("bad_response") + "\n" + ex.toString());
    } finally {
        GsonPool.getInstance().returnGson(gson);
    }
    return DocumentHelper.parseText(rpc.getResult()).getRootElement();
}
项目:xpath-to-xml    文件:XmlBuilderTest.java   
@Test
public void shouldBuildDocumentFromSetOfXPathsAndSetValues() throws XPathExpressionException, IOException {
    Map<String, Object> xmlProperties = fixtureAccessor.getXmlProperties();
    Document builtDocument = new XmlBuilder(namespaceContext)
            .putAll(xmlProperties)
            .build(DocumentHelper.createDocument());

    for (Entry<String, Object> xpathToValuePair : xmlProperties.entrySet()) {
        XPath xpath = builtDocument.createXPath(xpathToValuePair.getKey());
        if (null != namespaceContext) {
            xpath.setNamespaceContext(new SimpleNamespaceContextWrapper(namespaceContext));
        }
        assertThat(xpath.selectSingleNode(builtDocument).getText()).isEqualTo(xpathToValuePair.getValue());
    }
    assertThat(xmlToString(builtDocument)).isEqualTo(fixtureAccessor.getPutValueXml());
}
项目:joai-project    文件:User.java   
/**
 *  Description of the Method
 *
 *@return    Description of the Return Value
 */
private Element rolesMapToElement() {
    Element rolesElement = DocumentHelper.createElement("roles");
    if (!this.isAdminUser()) {
        for (Iterator i = this.getRoleMap().keySet().iterator(); i.hasNext(); ) {
            String collection = (String) i.next();

            // TODO - eliminate "default" collection. this can be removed after user files
            // for each User instance are written.

            Roles.Role role = this.getAssignedRole(collection);
            if (role != Roles.NO_ROLE) {
                Element roleElement = rolesElement.addElement("role");
                roleElement.addElement("rolename").setText(role.toString());
                roleElement.addElement("collection").setText(collection);

            }
        }
    }
    return rolesElement;
}
项目:joai-project    文件:DevelTools.java   
public static void addAgent (String id) throws Exception {
    NdrRequest request = new NdrRequest ();
    request.setObjectType(NDRObjectType.AGENT);
    request.setVerb ("addAgent");

    Element identifier = DocumentHelper.createElement("identifier");
    identifier.setText (id);
    identifier.addAttribute ("type", "HOST");
    request.addCommand ("property", identifier);
    request.addCommand ("relationship", "memberOf", "2200/test.20070806193858997T");
    String title = "Agent for mud collection";
    String description = "its all about mud";
    String subject = "none that i can see";
    NsdlDcWriter dc_stream = new NsdlDcWriter(title, description, subject);

    request.addDCStreamCmd(dc_stream.asElement());

    request.submit();
}
项目:WechatBot    文件:WechatBot.java   
private Map<String, String> parseInitData(String data) {
    try {
        Map<String, String> ussData = new HashMap<>();
        Document document = DocumentHelper.parseText(data);
        Element root = document.getRootElement();
        Iterator iter = root.elementIterator();
        while (iter.hasNext()) {
            Element ele = (Element) iter.next();
            log.debug("name:" + ele.getName() + " value:" + ele.getStringValue());
            ussData.put(ele.getName(), ele.getStringValue());
        }

        // 随机device id
        String deviceID = "e";
        for (int i = 0; i < 3; i++) {
            int randomNum = ThreadLocalRandom.current().nextInt(10000, 99999);
            deviceID += randomNum;
        }
        ussData.put("deviceID", deviceID);
        return ussData;
    } catch (DocumentException e) {
        e.printStackTrace();
    }
    return null;
}
项目:iBase4J    文件:XmlUtil.java   
/**
 * 将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;
}
项目:unitimes    文件:StudentSectioningQueue.java   
protected static void addItem(org.hibernate.Session hibSession, UserContext user, Long sessionId, Type type, Collection<Long> ids) {
    StudentSectioningQueue q = new StudentSectioningQueue();
    q.setTimeStamp(new Date());
    q.setType(type.ordinal());
    q.setSessionId(sessionId);
    Document d = DocumentHelper.createDocument();
    Element root = d.addElement("generic");
    if (user != null) {
        Element e = root.addElement("user");
        e.addAttribute("id", user.getExternalUserId()).setText(user.getName());
    }
    if (ids != null && !ids.isEmpty()) {
        for (Long id: ids)
            root.addElement("id").setText(id.toString());
    }
    q.setMessage(d);
    hibSession.save(q);
}
项目:JAVA-    文件:XmlUtil.java   
/**
 * 将List数据类型转换为符合XML格式规范的字符串(基于节点值的方式)
 * 
 * @param pList 传入的List数据(List对象可以是Dto、VO、Domain的属性集)
 * @param pRootNodeName 根节点名称
 * @param pFirstNodeName 行节点名称
 * @return string 返回XML格式字符串
 */
public static final String parseList2XmlBasedNode(List pList, String pRootNodeName, String pFirstNodeName) {
    Document document = DocumentHelper.createDocument();
    Element output = document.addElement(pRootNodeName);
    for (int i = 0; i < pList.size(); i++) {
        Map map = (Map) pList.get(i);
        Element elRow = output.addElement(pFirstNodeName);
        Iterator it = map.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            Element leaf = elRow.addElement((String) entry.getKey());
            leaf.setText(String.valueOf(entry.getValue()));
        }
    }
    String outXml = document.asXML().substring(39);
    return outXml;
}
项目:unitimes    文件:DataExchangeConnector.java   
@Override
public void doPost(ApiHelper helper) throws IOException {
    helper.getSessionContext().checkPermissionAnyAuthority(Right.ApiDataExchangeConnector);

    Document document = helper.getRequest(Document.class);
    Document output = DocumentHelper.createDocument();
    final Element messages = output.addElement("html");
    try {
        DataExchangeHelper.importDocument(document, helper.getSessionContext().isAuthenticated() ? helper.getSessionContext().getUser().getExternalUserId() : null, new LogWriter() {
            @Override
            public void println(String message) {
                messages.addElement("p").setText(message);
            }
        });
        helper.setResponse(output);
    } catch (Exception e) {
        throw new IOException(e.getMessage(), e);
    }
}
项目:urule    文件:FrameServletHandler.java   
public void fileSource(HttpServletRequest req, HttpServletResponse resp) throws Exception {
    String path=req.getParameter("path");
    path=Utils.decodeURL(path);
    InputStream inputStream=repositoryService.readFile(path,null);
    String content=IOUtils.toString(inputStream,"utf-8");
    inputStream.close();
    String xml=null;
    try{
        Document doc=DocumentHelper.parseText(content);
        OutputFormat format=OutputFormat.createPrettyPrint();
        StringWriter out=new StringWriter();
        XMLWriter writer=new XMLWriter(out, format);
        writer.write(doc);
        xml=out.toString();
    }catch(Exception ex){
        xml=content;
    }
    Map<String,Object> result=new HashMap<String,Object>();
    result.put("content", xml);
    writeObjectToJson(resp, result);
}
项目:iBase4J    文件:XmlUtil.java   
/**
 * 将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;
}
项目:urule    文件:RuleSetReferenceUpdater.java   
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);
    }
}
项目:sbc-qsystem    文件:QIndicatorHtmlboard.java   
@Override
public Element getConfig() {
    String tr = "<Параметры>\n"
        + "   <Параметер Наименование=\"top.size\" Тип=\"1\" Значение=\"" + HtmlBoardProps
        .getInstance().topSize + "\"/>\n"
        + "   <Параметер Наименование=\"top.url\" Тип=\"3\" Значение=\"" + HtmlBoardProps
        .getInstance().topUrl + "\"/>\n"
        + "   <Параметер Наименование=\"left.size\" Тип=\"1\" Значение=\"" + HtmlBoardProps
        .getInstance().leftSize + "\"/>\n"
        + "   <Параметер Наименование=\"left.url\" Тип=\"3\" Значение=\"" + HtmlBoardProps
        .getInstance().leftUrl + "\"/>\n"
        + "   <Параметер Наименование=\"right.size\" Тип=\"1\" Значение=\"" + HtmlBoardProps
        .getInstance().rightSize + "\"/>\n"
        + "   <Параметер Наименование=\"right.url\" Тип=\"3\" Значение=\"" + HtmlBoardProps
        .getInstance().rightUrl + "\"/>\n"
        + "   <Параметер Наименование=\"bottom.size\" Тип=\"1\" Значение=\"" + HtmlBoardProps
        .getInstance().bottomSize + "\"/>\n"
        + "   <Параметер Наименование=\"bottom.url\" Тип=\"3\" Значение=\"" + HtmlBoardProps
        .getInstance().bottomUrl + "\"/>\n"
        + "   <Параметер Наименование=\"need_reload\" Тип=\"4\" Значение=\"" + (
        HtmlBoardProps.getInstance().needReload ? "1" : "0") + "\"/>\n";

    for (String key : HtmlBoardProps.getInstance().getAddrs().keySet()) {
        tr = tr + "   <Параметер Наименование=\"" + key + "\" Тип=\"3\" Значение=\""
            + HtmlBoardProps
            .getInstance().getAddrs().get(key) + "\" " + Uses.TAG_BOARD_READ_ONLY
            + "=\"true\"/>\n";
    }

    tr = tr + "</Параметры>";
    final Document document;
    try {
        document = DocumentHelper.parseText(tr);
    } catch (DocumentException ex) {
        throw new ServerException(ex);
    }
    return document.getRootElement();
}
项目:iBase4J-Common    文件:XmlUtil.java   
/**
 * 将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) {
        logger.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;
}
项目:directory-ldap-api    文件:BatchRequestDsml.java   
/**
 * Converts this Batch Request to its XML representation in the DSMLv2 format.
 * 
 * @return the XML representation in DSMLv2 format
 */
public String toDsml()
{
    Document document = DocumentHelper.createDocument();
    Element element = document.addElement( "batchRequest" );

    // RequestID
    if ( requestID != 0 )
    {
        element.addAttribute( "requestID", Integer.toString( requestID ) );
    }

    // ResponseOrder
    if ( responseOrder == ResponseOrder.UNORDERED )
    {
        element.addAttribute( "responseOrder", "unordered" );
    }

    // Processing
    if ( processing == Processing.PARALLEL )
    {
        element.addAttribute( "processing", "parallel" );
    }

    // On Error
    if ( onError == OnError.RESUME )
    {
        element.addAttribute( "onError", "resume" );
    }

    // Requests
    for ( DsmlDecorator<? extends Request> request : requests )
    {
        request.toDsml( element );
    }

    return ParserUtils.styleDocument( document ).asXML();
}
项目:YiDu-Novel    文件:WeixinUtils.java   
/**
 * Give body, parse result to `result` map
 *
 * @param body
 * @param result
 * @throws DocumentException
 */
public static void parseWxMessage(String body, Map<String, String> result) throws DocumentException {
    Element root = DocumentHelper.parseText(body).getRootElement();
    for (Iterator i = root.elementIterator(); i.hasNext(); ) {
        Element element = (Element) i.next();
        result.put(element.getName(), element.getText());
    }
}
项目:zookeeper-test-demo    文件:ConfigUtil.java   
/**
 * 输出string为xml文件
 * 
 * @param xmlText
 *            xml内容
 * @param storePath
 *            保存路径
 * @throws Exception
 */
public static void writeToXML(String xmlText, String storePath) throws Exception {
    try {
        Document doc = DocumentHelper.parseText(xmlText);
        FileOutputStream xmlOs = new FileOutputStream(new File(storePath));
        byte[] data = xmlText.getBytes();
        xmlOs.write(data, 0, data.length);
        xmlOs.flush();

        xmlOs.close();
    } catch (Exception e) {
        throw new Exception("输入的xml文本有问题或者传入的路径有出入", e);
    }
}
项目:urule    文件:RepositoryServiceImpl.java   
@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;
}
项目:joai-project    文件:DataStreamWrapper.java   
public void setDataStream( String _format, String _metadataXML ) throws Exception { 
    if (_metadataXML == null)
        this.dataStreams.put (_format, null);
    else {
        Document doc = DocumentHelper.parseText(_metadataXML);
        this.setDataStream(_format, doc.getRootElement());
    }
}
项目:urule    文件:FlowDefinitionReferenceUpdater.java   
public boolean contain(String path, String xml) {
    try{
        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 filePath=ele.attributeValue("path");
            if(filePath.endsWith(path)){
                return true;
            }
        }
        return false;
    }catch(Exception ex){
        throw new RuleException(ex);
    }
}
项目:urule    文件:AbstractBuilder.java   
protected Element parseResource(String content){
    try {
        Document document = DocumentHelper.parseText(content);
        Element root=document.getRootElement();
        return root;
    } catch (DocumentException e) {
        throw new RuleException(e);
    }
}
项目:minlia-iot    文件:XmlSignatureAnnotationHelper.java   
/**
 * 预检验签名
 *
 * @param xml xml字符串
 * @param salt partnerApiKey
 * @param clazz 类型
 * @return 是否通过验证
 */
@SuppressWarnings("unchecked")
public static boolean prepareCheckSign(String xml, String salt, Boolean excludeSaltParameter,
    Class<?> clazz,
    SignatureAlgorithmic algorithmic, String saltParameterPrefix, String charset,
    CaseControl caseControl, String delimiter) {
  Field signField = signField(clazz);
  XmlElement xmlElementAnnotation = signField.getAnnotation(XmlElement.class);
  try {
    Document document = DocumentHelper.parseText(xml);
    Element rootElement = document.getRootElement();
    List<FieldPaired> fieldPaireds = new LinkedList<>();
    String targetSign = null;
    for (Iterator<Element> iterator = rootElement.elementIterator(); iterator.hasNext(); ) {
      Element element = iterator.next();
      if (element.getName().equals(xmlElementAnnotation.name())) {
        targetSign = element.getTextTrim();
      } else {
        String text = element.getTextTrim();
        if (StringUtils.isNotBlank(text)) {
          fieldPaireds.add(new FieldPaired(element.getName(), text));
        }
      }
    }
    if (StringUtils.isBlank(targetSign)) {
      log.warn("Sign shoud not be empty.");
    }
    String signStr = "";

    signStr = makeSignBySinpleFieldList(fieldPaireds, salt, excludeSaltParameter, algorithmic,
        saltParameterPrefix, charset, caseControl, delimiter);
    return signStr.equals(targetSign);
  } catch (DocumentException e) {
    e.printStackTrace();
    return false;
  }
}
项目:unitimes    文件:CurriculaCourseDemands.java   
@Override
public void teardown(org.hibernate.Session hibSession) {
    if (iUpdateClassification) {
        // Save into the cache
        Document doc = DocumentHelper.createDocument();
        iModel.saveAsXml(doc.addElement(getCacheName()), iAssignment);
        // sLog.debug("Model:\n" + doc.asXML());
        iClassification.setStudentsDocument(doc);

        hibSession.update(iClassification);
    }

    // Save results
    String majors = "";
    for (PosMajor major: iClassification.getCurriculum().getMajors()) {
        if (!majors.isEmpty()) majors += ",";
        majors += major.getCode();
    }
    for (CurStudent s: iModel.getStudents()) {
        WeightedStudentId student = new WeightedStudentId(- iLastStudentId.newId(), iClassification);
        if (iCreateStudentGroups)
            student.getGroups().add(new Group(-iClassification.getUniqueId(), iClassification.getCurriculum().getAbbv() + " " + iClassification.getAcademicClassification().getCode()));
        Set<WeightedCourseOffering> studentCourses = new HashSet<WeightedCourseOffering>();
        iStudentRequests.put(student.getStudentId(), studentCourses);
        Hashtable<Long, Double> priorities = new Hashtable<Long, Double>(); iEnrollmentPriorities.put(student.getStudentId(), priorities);
        for (CurCourse course: s.getCourses(iAssignment)) {
            CourseOffering co = iCourses.get(course.getCourseId());
            if (course.getPriority() != null) priorities.put(co.getUniqueId(), course.getPriority());
            Set<WeightedStudentId> courseStudents = iDemands.get(co.getUniqueId());
            if (courseStudents == null) {
                courseStudents = new HashSet<WeightedStudentId>();
                iDemands.put(co.getUniqueId(), courseStudents);
            }
            courseStudents.add(student);
            studentCourses.add(new WeightedCourseOffering(co, student.getWeight()));
        }
    }
}