public static void main(String[] args) { // TODO Auto-generated method stub SAXReader reader = new SAXReader(); try { Document document = reader.read(new File("books.xml")); Element bookStore = document.getRootElement(); Iterator it = bookStore.elementIterator(); while (it.hasNext()) { Element book = (Element) it.next(); List<org.dom4j.Attribute> bootAttrs = book.attributes(); for (org.dom4j.Attribute attr : bootAttrs) { System.out.println("node name: " + attr.getName() + " - node value: " + attr.getValue()); } Iterator itt = book.elementIterator(); while (itt.hasNext()) { Element bookChild = (Element) itt.next(); System.out.println( "sub node name: " + bookChild.getName() + " - sub node value: " + bookChild.getStringValue()); } System.out.println(); } } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
public static void parse(String xml) { Document doc = null; try { doc = DocumentHelper.parseText(xml); // 将字符串转为XML Element rootElt = doc.getRootElement(); // 获取根节点smsReport Iterator iters = rootElt.elementIterator("sendResp"); // 获取根节点下的子节点sms while (iters.hasNext()) { Element recordEle1 = (Element) iters.next(); Iterator iter = recordEle1.elementIterator("sms"); int i = 0; // 遍历sms节点 while (iter.hasNext()) { Element recordEle = (Element) iter.next(); String phone = recordEle.elementTextTrim("phone"); // 拿到sms节点下的子节点stat值 String smsID = recordEle.elementTextTrim("smsID"); // 拿到sms节点下的子节点stat值 System.out.println(phone + "===" + smsID); } } } catch (DocumentException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } }
void for_safety(Element el2) { for (Iterator n = el2.elementIterator(); n.hasNext(); ) { Element el21 = (Element) n.next(); if (el21.getName().equals("transition")) { int mark = 0; for (Iterator m = el21.elementIterator(); m.hasNext(); ) { Element el22 = (Element) m.next(); if (el22.getName().equals("mode") && mark == 0) { mark = 1; tl[tl_index].source_com = component_num - 1; tl[tl_index].source_state = find_state(el22.attributeValue("IDREF"), component_num - 1); continue; } if (el22.getName().equals("trigger")) { for (Iterator p = el22.elementIterator(); p.hasNext(); ) { Element el23 = (Element) p.next(); if (el23.getName().equals("event")) { tl[tl_index].event = el23.attributeValue("name"); } } continue; } if (el22.getName().equals("mode") && mark == 1) { tl[tl_index].target_com = component_num - 1; tl[tl_index++].target_state = find_state(el22.attributeValue("IDREF"), component_num - 1); } } } } }
/** * 通过Title 查询是相似分类信息 * * @param xml * @return * @throws DocumentException */ public static List<TradingReseCategory> selectCategoryByKey(String xml) throws Exception { List<TradingReseCategory> litrc = new ArrayList(); // 商品分类目录查询 Document document = formatStr2Doc(xml); Element rootElt = document.getRootElement(); if (rootElt == null) { return litrc; } Element recommend = rootElt.element("SuggestedCategoryArray"); if (recommend == null) { return litrc; } Iterator<Element> ite = recommend.elementIterator("SuggestedCategory"); while (ite.hasNext()) { Element ele = ite.next(); Element cate = ele.element("Category"); Element PercentItemFound = ele.element("PercentItemFound"); TradingReseCategory trc = new TradingReseCategory(); trc.setId(Long.parseLong(cate.elementText("CategoryID"))); trc.setCategoryId(cate.elementText("CategoryID")); Iterator<Element> ites = cate.elementIterator("CategoryParentName"); String cateName = ""; while (ites.hasNext()) { Element ent = ites.next(); cateName = cateName + ent.getText() + ":"; } trc.setCategoryKey(PercentItemFound.getText() + "%"); trc.setCategoryName(cateName + cate.elementText("CategoryName")); litrc.add(trc); } return litrc; }
/** * 解析subscribes * * @param String consumerName 消费者名称 * @param Element consumerNode consumer节点 */ private void parseSubscribes(String consumerName, Element consumerNode) { List<Subscribe> subscribesList = new ArrayList<Subscribe>(); Map<String, Map<String, Strategy>> topicTagStrategyMap = new HashMap<String, Map<String, Strategy>>(); for (Iterator<?> topic = consumerNode.elementIterator(); topic.hasNext(); ) { Element topicNode = (Element) topic.next(); String topicName = topicNode.attributeValue("name"); Map<String, Strategy> tagStrategyMap = new HashMap<String, Strategy>(); StringBuffer tagsSb = new StringBuffer(); for (Iterator<?> tag = topicNode.elementIterator(); tag.hasNext(); ) { Element tagNode = (Element) tag.next(); String tagName = tagNode.attributeValue("name"); tagsSb.append(tagName); if (tag.hasNext()) { tagsSb.append("||"); } Strategy strategy = this.parseStrategys(tagNode); tagStrategyMap.put(tagName, strategy); } String tags = tagsSb.toString(); Subscribe subscribe = new Subscribe(); subscribe.setTopic(topicName); subscribe.setTags(tags); subscribesList.add(subscribe); topicTagStrategyMap.put(topicName, tagStrategyMap); } this.subscribes.put(consumerName, subscribesList); this.strategys.put(consumerName, topicTagStrategyMap); }
/** 功能:XML报文解析函数 */ public static HashMap GetMessage(String url) { SAXReader reader = new SAXReader(); Document doc = null; HashMap hm = null; try { InputStream in = new URL(url).openStream(); if (in != null) { doc = reader.read(in); hm = new HashMap(); Element root = doc.getRootElement(); for (Iterator it = root.elementIterator(); it.hasNext(); ) { Element e = (Element) it.next(); if (e.nodeCount() > 1) { HashMap hm1 = new HashMap(); for (Iterator it1 = e.elementIterator(); it1.hasNext(); ) { Element e1 = (Element) it1.next(); hm1.put(e1.getName(), e1.getText()); } hm.put(e.getName(), hm1); } else { hm.put(e.getName(), e.getText()); } } } doc.clearContent(); in.close(); } catch (DocumentException e) { e.printStackTrace(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return hm; }
/** * Method readData. * * @param rootElement Element * @throws Exception */ @Override protected void readData(Element rootElement) throws Exception { for (Iterator<Element> iterator = rootElement.elementIterator(); iterator.hasNext(); ) { Element listElement = iterator.next(); if ("domain".equals(listElement.getName())) { int id = Integer.parseInt(listElement.attributeValue("id")); Territory territory = null; for (Iterator<Element> i = listElement.elementIterator(); i.hasNext(); ) { Element n = i.next(); if ("polygon".equalsIgnoreCase(n.getName())) { Polygon shape = ZoneParser.parsePolygon(n); if (!shape.validate()) { error("DomainParser: invalid territory data : " + shape + "!"); } if (territory == null) { territory = new Territory(); } territory.add(shape); } } if (territory == null) { throw new RuntimeException("DomainParser: empty territory!"); } getHolder().addRegionData(new DomainArea(id, territory)); } } }
/** * @see * org.springframework.extensions.config.xml.elementreader.ConfigElementReader#parse(org.dom4j.Element) */ @SuppressWarnings("unchecked") public ConfigElement parse(Element element) { OpenSearchConfigElement configElement = null; if (element != null) { String elementName = element.getName(); if (elementName.equals(ELEMENT_OPENSEARCH) == false) { throw new ConfigException( "OpenSearchElementReader can only parse " + ELEMENT_OPENSEARCH + "elements, the element passed was '" + elementName + "'"); } // go through the registered engines configElement = new OpenSearchConfigElement(); Element pluginsElem = element.element(ELEMENT_ENGINES); if (pluginsElem != null) { Iterator<Element> engines = pluginsElem.elementIterator(ELEMENT_ENGINE); while (engines.hasNext()) { // construct engine Element engineElem = engines.next(); String label = engineElem.attributeValue(ATTR_LABEL); String labelId = engineElem.attributeValue(ATTR_LABEL_ID); String proxy = engineElem.attributeValue(ATTR_PROXY); EngineConfig engineCfg = new EngineConfig(label, labelId, proxy); // construct urls for engine Iterator<Element> urlsConfig = engineElem.elementIterator(ELEMENT_URL); while (urlsConfig.hasNext()) { Element urlConfig = urlsConfig.next(); String type = urlConfig.attributeValue(ATTR_TYPE); String url = urlConfig.getTextTrim(); engineCfg.addUrl(type, url); } // register engine config configElement.addEngine(engineCfg); } } // extract proxy configuration String url = null; Element proxyElem = element.element(ELEMENT_PROXY); if (proxyElem != null) { Element urlElem = proxyElem.element(ELEMENT_URL); if (urlElem != null) { url = urlElem.getTextTrim(); ProxyConfig proxyCfg = new ProxyConfig(url); configElement.setProxy(proxyCfg); } } } return configElement; }
private static void getCourseListAction() { // System.out.println("-------getXml运行了---------"); String xml = HttpUtil.getXMLfromServer(); // 得到xml字符串 CourseList courseList = new CourseList(); Document doc = null; try { // 读取并解析XML文档 // SAXReader就是一个管道,用一个流的方式,把xml文件读出来 // // SAXReader reader = new SAXReader(); //User.hbm.xml表示你要解析的xml文档 // Document document = reader.read(new File("User.hbm.xml")); // 下面的是通过解析xml字符串的 doc = (Document) DocumentHelper.parseText(xml); // 将字符串转为XML Element rootElt = doc.getRootElement(); // 获取根节点 // System.out.println("根节点:" + rootElt.getName()); // 拿到根节点的名称 Iterator courseiter = rootElt.elementIterator("Course"); // 获取根节点下的子节点Course // 遍历Course节点 while (courseiter.hasNext()) { Course course = new Course(); Element couurseelement = (Element) courseiter.next(); course.setName(couurseelement.attributeValue("CourseName")); // 获取课程名称 // 这里对Course节点下面的操作 Iterator chapteriter = couurseelement.elementIterator("Chapter"); // 得到course节点的子节点Chapter while (chapteriter.hasNext()) { Chapter chapter = new Chapter(); Element chapterelement = (Element) chapteriter.next(); chapter.setName(chapterelement.attributeValue("ChapterName")); // 获取章节名称 // 这里对Chapter节点下面做解析 Iterator pageiter = chapterelement.elementIterator("Page"); // 得到Chapter节点的子节点Page while (pageiter.hasNext()) { Element pageelement = (Element) pageiter.next(); Page page = new Page(); page.setName(pageelement.getText()); chapter.pagelist.add(page); // System.out.println(pageelement.getText()); } course.chapterlist.add(chapter); // 添加章节到课程中 // System.out.println(chapter.ChacapterName); } courseList.courselist.add(course); // 添加课程到List中 // System.out.println(course.CourseName); } } catch (Exception e) { e.printStackTrace(); } courses = courseList; }
/** * 遍历整个XML文件,获取所有节点的值与其属性的值,并放入HashMap中 * * @param filename String 待遍历的XML文件(相对路径或者绝对路径) * @param hm HashMap 存放遍历结果,格式:<nodename,nodevalue>或者<nodename+attrname,attrvalue> */ public void iterateWholeXML(String filename, HashMap<String, String> hm) { SAXReader saxReader = new SAXReader(); try { Document document = saxReader.read(new File(filename)); Element root = document.getRootElement(); // 用于记录学生编号的变量 int num = -1; // 遍历根结点(students)的所有孩子节点(肯定是student节点) for (Iterator iter = root.elementIterator(); iter.hasNext(); ) { Element element = (Element) iter.next(); num++; // 获取person节点的age属性的值 Attribute ageAttr = element.attribute("age"); if (ageAttr != null) { String age = ageAttr.getValue(); if (age != null && !age.equals("")) { hm.put(element.getName() + "-" + ageAttr.getName() + num, age); } else { hm.put(element.getName() + "-" + ageAttr.getName() + num, "20"); } } else { hm.put(element.getName() + "-age" + num, "20"); } // 遍历student结点的所有孩子节点(即name,college,telphone,notes),并进行处理 for (Iterator iterInner = element.elementIterator(); iterInner.hasNext(); ) { Element elementInner = (Element) iterInner.next(); if (elementInner.getName().equals("college")) { hm.put(elementInner.getName() + num, elementInner.getText()); // 获取college节点的leader属性的值 Attribute leaderAttr = elementInner.attribute("leader"); if (leaderAttr != null) { String leader = leaderAttr.getValue(); if (leader != null && !leader.equals("")) { hm.put(elementInner.getName() + "-" + leaderAttr.getName() + num, leader); } else { hm.put(elementInner.getName() + "-" + leaderAttr.getName() + num, "leader"); } } else { hm.put(elementInner.getName() + "-leader" + num, "leader"); } } else { hm.put(elementInner.getName() + num, elementInner.getText()); } } } } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
@Override protected void readData(Element rootElement) throws Exception { for (Iterator<Element> iterator = rootElement.elementIterator(); iterator.hasNext(); ) { Element e = iterator.next(); if ("fish".equals(e.getName())) { MultiValueSet<String> map = new MultiValueSet<String>(); for (Iterator<Attribute> attributeIterator = e.attributeIterator(); attributeIterator.hasNext(); ) { Attribute attribute = attributeIterator.next(); map.put(attribute.getName(), attribute.getValue()); } getHolder().addFish(new FishTemplate(map)); } else if ("lure".equals(e.getName())) { MultiValueSet<String> map = new MultiValueSet<String>(); for (Iterator<Attribute> attributeIterator = e.attributeIterator(); attributeIterator.hasNext(); ) { Attribute attribute = attributeIterator.next(); map.put(attribute.getName(), attribute.getValue()); } Map<FishGroup, Integer> chances = new HashMap<FishGroup, Integer>(); for (Iterator<Element> elementIterator = e.elementIterator(); elementIterator.hasNext(); ) { Element chanceElement = elementIterator.next(); chances.put( FishGroup.valueOf(chanceElement.attributeValue("type")), Integer.parseInt(chanceElement.attributeValue("value"))); } map.put("chances", chances); getHolder().addLure(new LureTemplate(map)); } else if ("distribution".equals(e.getName())) { int id = Integer.parseInt(e.attributeValue("id")); for (Iterator<Element> forLureIterator = e.elementIterator(); forLureIterator.hasNext(); ) { Element forLureElement = forLureIterator.next(); LureType lureType = LureType.valueOf(forLureElement.attributeValue("type")); Map<FishGroup, Integer> chances = new HashMap<FishGroup, Integer>(); for (Iterator<Element> chanceIterator = forLureElement.elementIterator(); chanceIterator.hasNext(); ) { Element chanceElement = chanceIterator.next(); chances.put( FishGroup.valueOf(chanceElement.attributeValue("type")), Integer.parseInt(chanceElement.attributeValue("value"))); } getHolder().addDistribution(id, lureType, chances); } } } }
/** * 得到反馈信息列表 * * @param xml * @return * @throws DocumentException */ public static List<TradingFeedBackDetail> getFeedBackListElement(String xml) throws Exception { List<TradingFeedBackDetail> lifb = new ArrayList(); Document document = formatStr2Doc(xml); Element rootElt = document.getRootElement(); Element recommend = rootElt.element("FeedbackDetailArray"); Iterator<Element> iter = recommend.elementIterator("FeedbackDetail"); while (iter.hasNext()) { Element element = iter.next(); TradingFeedBackDetail tfbd = new TradingFeedBackDetail(); tfbd.setCommentinguser(element.elementText("CommentingUser")); tfbd.setCommentinguserscore(Long.parseLong(element.elementText("CommentingUserScore"))); tfbd.setCommenttext( StringEscapeUtils.escapeXml(element.element("CommentText").getStringValue())); tfbd.setCommenttime(DateUtils.returnDate(element.elementText("CommentTime"))); tfbd.setCommenttype(element.elementText("CommentType")); tfbd.setItemid(element.elementText("ItemID")); tfbd.setRole(element.elementText("Role")); tfbd.setFeedbackid(element.elementText("FeedbackID")); tfbd.setTransactionid(element.elementText("TransactionID")); tfbd.setOrderlineitemid(element.elementText("OrderLineItemID")); tfbd.setItemtitle(element.elementText("ItemTitle")); tfbd.setCreateTime(new Date()); if (element.elementText("ItemPrice") != null) { tfbd.setItemprice(Double.parseDouble(element.elementText("ItemPrice"))); } lifb.add(tfbd); } return lifb; }
// <dateformats> // <dateformat format="yahoo-csv" order="mdy" /> // ... // </dateformats> private static void populateDateFormatInfo(Element dateFormats) { dateOrderInfo = new HashMap<String, String>(); for (Iterator elements = dateFormats.elementIterator(DATEFORMAT); elements.hasNext(); ) { Element dateFormat = (Element) elements.next(); String origOrder = dateFormat.attributeValue(ATTR_ORDER); if (origOrder == null || origOrder.isEmpty()) { continue; } String order = origOrder.toLowerCase(); if (!(order.equals("ymd") || order.equals("ydm") || order.equals("myd") || order.equals("mdy") || order.equals("dmy") || order.equals("dym"))) { LOG.debug("invalid \"order\" %s in zimbra-contact-fields.xml", origOrder); continue; } String format = dateFormat.attributeValue(ATTR_FORMAT); if (format == null || format.isEmpty()) { continue; } String myLocale = dateFormat.attributeValue(ATTR_LOCALE); if (myLocale != null && !myLocale.isEmpty()) { format = format + "/" + myLocale; } dateOrderInfo.put(format, order); } }
public void readSiteContent(final ZipEntry entry, final String xml) throws DocumentException, DaoTaskException { Document doc = DocumentHelper.parseText(xml); Element root = doc.getRootElement(); for (Iterator<Element> i = root.elementIterator(); i.hasNext(); ) { Element element = i.next(); if (element.getName().equals("config")) { getConfigExporter().readConfigs(element); } if (element.getName().equals("pages")) { getPageExporter().readPages(element); } if (element.getName().equals("forms")) { getFormExporter().readForms(element); } if (element.getName().equals("users")) { getUserExporter().readUsers(element); } if (element.getName().equals("groups")) { getGroupExporter().readGroups(element); } if (element.getName().equals("folders")) { getFolderExporter().readFolders(element); } if (element.getName().equals("messages")) { getMessagesExporter().readMessages(element); } if (element.getName().equals("structures")) { getStructureExporter().readStructures(element); } if (element.getName().equals("plugins")) { getPluginExporter().readPlugins(element); } } }
/** * Load schema. * * @param schema the schema * @param schemaElement the schema element * @return the map * @throws Exception the exception */ @SuppressWarnings("unchecked") private static Map<String, Object> loadSchema( Schema schema, org.dom4j.Element schemaElement, ServiceContext ctx) throws Exception { String schemaName1 = schemaElement.attributeValue( ExportConstants.NAME_ATTR); // FIXME: Do we need this local var? String schemaName = schema.getName(); Map<String, Object> data = new HashMap<String, Object>(); Iterator<org.dom4j.Element> it = schemaElement.elementIterator(); while (it.hasNext()) { org.dom4j.Element element = it.next(); String name = element.getName(); Field field = schema.getField(name); if (field != null) { Object value = getElementData(element, field.getType(), ctx); data.put(name, value); } else { // FIXME: substitute an appropriate constant for "csid" below. // One potential class to which to add that constant, if it is not already // declared, might be AbstractCollectionSpaceResourceImpl - ADR 2012-09-24 if (!name.equals("csid")) { // 'csid' elements in input payloads can be safely ignored. logger.warn( "Invalid input document. No such property was found [" + name + "] in schema " + schemaName); } } } return data; }
public static boolean setParamsInListFromXML(ParameterList paramList, Element paramListEl) { boolean failure = false; for (ParameterAPI<?> param : paramList) { Iterator<Element> it = paramListEl.elementIterator(); boolean matched = false; while (it.hasNext()) { Element el = it.next(); if (param.getName().equals(el.attribute("name").getValue())) { matched = true; // System.out.println("Found a match!"); if (param.setValueFromXMLMetadata(el)) { // System.out.println("Parameter set successfully!"); } else { System.err.println("Parameter could not be set from XML!"); System.err.println( "It is possible that the parameter type doesn't yet support loading from XML"); failure = true; } } } if (!matched) { System.err.println( "Parameter '" + param.getName() + "' from XML can not be set because it can't be" + " found in the given ParameterList!"); failure = true; } } return !failure; }
/** * * 根据项目名获取项目所在的view名 * * @param projectName * @return */ public static String getProjectViewByProjectName(String projectName) { Document doc = null; try { doc = new SAXReader().read("/usr/share/tomcat6/.hudson/config.xml"); Element rootEle = doc.getRootElement(); Element viewEle = rootEle.element("views"); Iterator<Element> listViewIt = viewEle.elementIterator("listView"); while (listViewIt.hasNext()) { Element listViewEle = listViewIt.next(); String viewName = listViewEle.elementText("name"); Iterator<Element> projectNamesIt = listViewEle.element("jobNames").elementIterator("string"); while (projectNamesIt.hasNext()) { if (projectName.equals(projectNamesIt.next().getStringValue())) return viewName; } } } catch (DocumentException e) { System.out.println( "preAntInitTool --> XMLTools --> getProjectViewByProjectName() : DocumentException"); } catch (Exception e) { System.out.println( "preAntInitTool --> XMLTools --> getProjectViewByProjectName() : Exception"); } finally { doc = null; } return null; }
/** * @see * org.springframework.extensions.config.xml.elementreader.ConfigElementReader#parse(org.dom4j.Element) */ @SuppressWarnings("unchecked") public ConfigElement parse(Element element) { ConstraintHandlersConfigElement result = null; if (element == null) { return null; } String name = element.getName(); if (!name.equals(ELEMENT_CONSTRAINT_HANDLERS)) { throw new ConfigException( this.getClass().getName() + " can only parse " + ELEMENT_CONSTRAINT_HANDLERS + " elements, the element passed was '" + name + "'"); } result = new ConstraintHandlersConfigElement(); Iterator<Element> xmlNodes = element.elementIterator(); while (xmlNodes.hasNext()) { Element nextNode = xmlNodes.next(); String type = nextNode.attributeValue(ATTR_TYPE); String validationHandler = nextNode.attributeValue(ATTR_VALIDATOR_HANDLER); String message = nextNode.attributeValue(ATTR_MESSAGE); String messageId = nextNode.attributeValue(ATTR_MESSAGE_ID); String event = nextNode.attributeValue(ATTR_EVENT); result.addDataMapping(type, validationHandler, message, messageId, event); } return result; }
public static List<QueryPVisitor> confirmTicket(List<Long> ticketList) throws DataException, IOException, DocumentException { String msgIdValue = System.currentTimeMillis() + ""; String reqIdValue = "802"; StringBuffer sb = new StringBuffer(); for (Long id : ticketList) { sb.append(id + ","); } sb.delete(sb.length() - 1, sb.length()); Map<String, String> ParamMap = new LinkedHashMap<String, String>(); ParamMap.put("ReqId", reqIdValue); ParamMap.put("MsgId", msgIdValue); ParamMap.put("ReqParam", sb.toString()); ParamMap.put("ReqKey", MD5.md5(reqIdValue + msgIdValue + sb.toString() + key).toLowerCase()); String returnString = HttpclientUtil.Utf8HttpClientUtils(reUrl, ParamMap); Document doc = DocumentHelper.parseText(returnString); Element root = doc.getRootElement(); Element ticket; QueryPVisitor queryPVisitor; List<QueryPVisitor> returnTicketList = Lists.newArrayList(); for (Iterator i = root.elementIterator("Ticket"); i.hasNext(); ) { ticket = (Element) i.next(); queryPVisitor = new QueryPVisitor(); ticket.accept(queryPVisitor); returnTicketList.add(queryPVisitor); } if (returnTicketList.isEmpty()) { Document document = DocumentHelper.parseText(returnString); queryPVisitor = new QueryPVisitor(); document.accept(queryPVisitor); returnTicketList.add(queryPVisitor); } return returnTicketList; }
/** * Get the list of public 'claim' or 'counterclaim' or 'subclaim' * * @param parentClaimId the id of the parent claim * @param claimType 'claim' or 'counterclaim' or 'subclaim' * @return the list of public 'claim' or 'counterclaim' or 'subclaim' */ @SuppressWarnings("rawtypes") public List<Claim> getPublicClaims(String parentId, String claimType) { List<Claim> counterclaimList = new ArrayList<Claim>(); Element claimE; Claim claim; for (Iterator i = root.elementIterator(claimType); i.hasNext(); ) { claimE = (Element) i.next(); if (claimE.element("isDeleted").getText().equals("false") && claimE.element("parentId").getText().equals(parentId)) { String id = claimE.element("id").getText(), title = claimE.element("title").getText(), description = claimE.element("description").getText(), type = claimE.element("type").getText(), timeAdded = claimE.element("timeAdded").getText(), name = claimE.element("name").getText(), debateId = claimE.element("debateId").getText(), dialogType = claimE.elementText("dialogType"), teams = claimE.attributeValue("team"); claim = new Claim( id, title, description, type, timeAdded, parentId, name, debateId, dialogType, teams); counterclaimList.add(claim); } } return counterclaimList; }
public static void setupLocalSolver(String codeBase, String host, int port) { if (sInstance == null || sLocalSolverInitialized) return; synchronized (sInstance) { try { File webInfDir = new File(ApplicationProperties.getBasePath()); File timetablingDir = webInfDir.getParentFile(); File solverDir = new File(timetablingDir, "solver"); File solverJnlp = new File(solverDir, "solver.jnlp"); Document document = (new SAXReader()).read(solverJnlp); Element root = document.getRootElement(); root.attribute("codebase") .setValue(codeBase + (codeBase.endsWith("/") ? "" : "/") + "solver"); boolean hostSet = false, portSet = false; Element resources = root.element("resources"); for (Iterator i = resources.elementIterator("property"); i.hasNext(); ) { Element property = (Element) i.next(); if ("tmtbl.solver.register.host".equals(property.attributeValue("name"))) { property.attribute("value").setValue(host); hostSet = true; } if ("tmtbl.solver.register.port".equals(property.attributeValue("name"))) { property.attribute("value").setValue(String.valueOf(port)); portSet = true; } } if (!hostSet) { resources .addElement("property") .addAttribute("name", "tmtbl.solver.register.host") .addAttribute("value", host); } if (!portSet) { resources .addElement("property") .addAttribute("name", "tmtbl.solver.register.port") .addAttribute("value", String.valueOf(port)); } FileOutputStream fos = null; try { fos = new FileOutputStream(solverJnlp); (new XMLWriter(fos, OutputFormat.createPrettyPrint())).write(document); fos.flush(); fos.close(); fos = null; } finally { try { if (fos != null) fos.close(); } catch (IOException e) { } } } catch (Exception e) { sLog.debug("Unable to alter solver.jnlp, reason: " + e.getMessage(), e); } sLocalSolverInitialized = true; } }
private void loadFlashs(Element node, Tutorial tutorial) { for (Iterator<?> iter = node.elementIterator(); iter.hasNext(); ) { Element child = (Element) iter.next(); String name = child.getName(); if (name.equals("flash")) loadFlash(child, tutorial); } }
// 解析价格跟踪 public static List<TradingPriceTracking> getPriceTrackingItemByItemId(String res) throws Exception { List<TradingPriceTracking> priceTrackings = new ArrayList<TradingPriceTracking>(); Document document = formatStr2Doc(res); Element rootElt = document.getRootElement(); Iterator items = rootElt.elementIterator("Item"); while (items.hasNext()) { TradingPriceTracking priceTracking = new TradingPriceTracking(); Element item = (Element) items.next(); priceTracking.setItemid(SamplePaseXml.getSpecifyElementText(item, "ItemID")); priceTracking.setTitle(SamplePaseXml.getSpecifyElementText(item, "Title")); priceTracking.setCurrentprice( SamplePaseXml.getSpecifyElementText(item, "ConvertedCurrentPrice")); priceTracking.setBidcount(SamplePaseXml.getSpecifyElementText(item, "BidCount")); Element ConvertedCurrentPrice = item.element("ConvertedCurrentPrice"); String endtime = SamplePaseXml.getSpecifyElementText(item, "EndTime"); if (StringUtils.isNotBlank(endtime)) { priceTracking.setEndtime(DateUtils.returnDate(endtime)); } String currencyId1 = ""; if (ConvertedCurrentPrice != null) { Attribute currencyId = ConvertedCurrentPrice.attribute("currencyId"); if (currencyId != null) { currencyId1 = currencyId.getValue(); } } priceTracking.setCurrencyid(currencyId1); priceTrackings.add(priceTracking); } return priceTrackings; }
/** * 解析微信xml消息 * * @param content 微信端的xml数据 * @return 转换之后的对象 */ public static ReceiveXmlEntity getMsgEntity(String content) { ReceiveXmlEntity msg = null; try { // 将字符串转换为XML对象 Document doc = DocumentHelper.parseText(content); // 获取文档的节点 Element root = doc.getRootElement(); // 遍历根节点下所有的子节点 Iterator<?> iter = root.elementIterator(); // 利用反射机制,调用对象的set方法 Class<?> c = Class.forName("com.wechat.entity.ReceiveXmlEntity"); // 创建实体类 msg = (ReceiveXmlEntity) c.newInstance(); while (iter.hasNext()) { Element ele = (Element) iter.next(); // 获取set方法中的参数字段(实体类的属性) Field filed = c.getDeclaredField(ele.getName()); // 获取set方法 Method method = c.getDeclaredMethod("set" + ele.getName(), filed.getType()); // 调用set方法 method.invoke(msg, ele.getText()); } } catch (Exception e) { e.printStackTrace(); } return msg; }
/** * This will take a DSML <code>Element</code> containing an entry of type <dsml:entry * name="name"/> and convert it to an LDAP entry. * * @param entryElement <code>Element</code> of DSML content * @return <code>LdapEntry</code> */ protected LdapEntry createSearchResult(final Element entryElement) { final LdapEntry ldapEntry = new LdapEntry(); ldapEntry.setDn(""); if (entryElement != null) { final String name = entryElement.attributeValue("dn"); if (name != null) { ldapEntry.setDn(name); } if (entryElement.hasContent()) { final Iterator<?> ocIterator = entryElement.elementIterator("objectclass"); while (ocIterator.hasNext()) { final Element ocElement = (Element) ocIterator.next(); if (ocElement != null && ocElement.hasContent()) { final String ocName = "objectClass"; final LdapAttribute ldapAttribute = new LdapAttribute(ocName); final Iterator<?> valueIterator = ocElement.elementIterator("oc-value"); while (valueIterator.hasNext()) { final Element valueElement = (Element) valueIterator.next(); if (valueElement != null) { final String value = valueElement.getText(); if (value != null) { final String encoding = valueElement.attributeValue("encoding"); if (encoding != null && encoding.equals("base64")) { ldapAttribute.getValues().add(LdapUtil.base64Decode(value)); } else { ldapAttribute.getValues().add(value); } } } } ldapEntry.getLdapAttributes().addAttribute(ldapAttribute); } } ldapEntry .getLdapAttributes() .addAttributes( super.createSearchResult(entryElement).getLdapAttributes().getAttributes()); } } return ldapEntry; }
/** * Extracts a list of extended service discovery information from an IQ packet. * * @param packet the packet * @return a list of extended service discoverin information features. */ private static List<String> getExtendedDataForms(IQ packet) { List<String> results = new ArrayList<String>(); Element query = packet.getChildElement(); @SuppressWarnings("unchecked") Iterator<Element> extensionIterator = query.elementIterator(QName.get("x", "jabber:x:data")); if (extensionIterator != null) { while (extensionIterator.hasNext()) { Element extensionElement = extensionIterator.next(); final StringBuilder formType = new StringBuilder(); @SuppressWarnings("unchecked") Iterator<Element> fieldIterator = extensionElement.elementIterator("field"); List<String> vars = new ArrayList<String>(); while (fieldIterator != null && fieldIterator.hasNext()) { final Element fieldElement = fieldIterator.next(); if (fieldElement.attributeValue("var").equals("FORM_TYPE")) { formType.append(fieldElement.element("value").getText()); formType.append('<'); } else { final StringBuilder var = new StringBuilder(); var.append(fieldElement.attributeValue("var")); var.append('<'); @SuppressWarnings("unchecked") Iterator<Element> valIter = fieldElement.elementIterator("value"); List<String> values = new ArrayList<String>(); while (valIter != null && valIter.hasNext()) { Element value = valIter.next(); values.add(value.getText()); } Collections.sort(values); for (String v : values) { var.append(v); var.append('<'); } vars.add(var.toString()); } } Collections.sort(vars); for (String v : vars) { formType.append(v); } results.add(formType.toString()); } } return results; }
void traverseXML() { Document document = null; try { SAXReader saxReader = new SAXReader(); document = saxReader.read(saFilePath); // 读取XML文件,获得document对象 } catch (Exception ex) { ex.printStackTrace(); } Element root = document.getRootElement(); for (Iterator i = root.elementIterator(); i.hasNext(); ) { Element el = (Element) i.next(); if (el.getName().equals("arch")) { for (Iterator j = el.elementIterator(); j.hasNext(); ) { Element el1 = (Element) j.next(); if (el1.getName().equals("event")) { event[event_index++] = el1.attributeValue("ID"); event_tag[event_index - 1] = el1.attributeValue("probability"); } if (el1.getName().equals("node")) { String node_name = el1.attributeValue("name"); component[component_num++] = node_name; for (Iterator k = el1.elementIterator(); k.hasNext(); ) { Element el2 = (Element) k.next(); if (el2.getName().equals("attribute")) { states[component_num - 1][states_index[component_num - 1]++] = el2.attributeValue("ID"); states_tag[component_num - 1][states_index[component_num - 1] - 1] = el2.attributeValue("tag"); } if (el2.getName().equals("SafetySpecification")) { for_safety(el2); } if (el2.getName().equals("port")) { for (Iterator m = el2.elementIterator(); m.hasNext(); ) { Element el21 = (Element) m.next(); if (el21.getName().equals("SafetySpecification")) { for_safety(el21); } } } } } } } } }
public static List<TradingPriceTracking> getPriceTrackingItem(String res, String title) throws Exception { List<TradingPriceTracking> list = new ArrayList<TradingPriceTracking>(); Document document = formatStr2Doc(res); Element rootElt = document.getRootElement(); Element searchResult = rootElt.element("searchResult"); Iterator items = searchResult.elementIterator("item"); while (items.hasNext()) { TradingPriceTracking priceTracking = new TradingPriceTracking(); Element item = (Element) items.next(); priceTracking.setItemid(SamplePaseXml.getSpecifyElementText(item, "itemId")); priceTracking.setCategoryid( SamplePaseXml.getSpecifyElementText(item, "primaryCategory", "categoryId")); priceTracking.setCategoryname( SamplePaseXml.getSpecifyElementText(item, "primaryCategory", "categoryName")); priceTracking.setCurrentprice( SamplePaseXml.getSpecifyElementText(item, "sellingStatus", "currentPrice")); priceTracking.setSellerusername( SamplePaseXml.getSpecifyElementText(item, "sellerInfo", "sellerUserName")); priceTracking.setTitle(SamplePaseXml.getSpecifyElementText(item, "title")); priceTracking.setBidcount( SamplePaseXml.getSpecifyElementText(item, "sellingStatus", "bidCount")); priceTracking.setPictureurl(SamplePaseXml.getSpecifyElementText(item, "galleryURL")); String starttime = SamplePaseXml.getSpecifyElementText(item, "listingInfo", "startTime"); String endtime = SamplePaseXml.getSpecifyElementText(item, "listingInfo", "endTime"); if (StringUtils.isNotBlank(starttime)) { priceTracking.setStarttime(DateUtils.returnDate(starttime)); } if (StringUtils.isNotBlank(endtime)) { priceTracking.setEndtime(DateUtils.returnDate(endtime)); } Element sellingStatus = item.element("sellingStatus"); String currencyId1 = ""; if (sellingStatus != null) { Element currentPrice = sellingStatus.element("currentPrice"); if (currentPrice != null) { Attribute currencyId = currentPrice.attribute("currencyId"); if (currencyId != null) { currencyId1 = currencyId.getValue(); } } } priceTracking.setCurrencyid(currencyId1); Element shippingInfo = item.element("shippingInfo"); if (shippingInfo != null) { Element shippingServiceCost = shippingInfo.element("shippingServiceCost"); if (shippingServiceCost != null) { Attribute shippingcurrencyId = shippingServiceCost.attribute("currencyId"); if (shippingcurrencyId != null) { priceTracking.setShippingcurrencyid(shippingcurrencyId.getValue()); } priceTracking.setShippingservicecost(shippingServiceCost.getTextTrim()); } } priceTracking.setQuerytitle(title); list.add(priceTracking); } return list; }
/** * 修改XML文件中内容,并另存为一个新文件 重点掌握dom4j中如何添加节点,修改节点,删除节点 * * @param filename 修改对象文件 * @param newfilename 修改后另存为该文件 * @return 返回操作结果, 0表失败, 1表成功 */ public int modifyXMLFile(String filename, String newfilename) { int returnValue = 0; SAXReader saxReader = new SAXReader(); Document doc = null; try { /** 修改内容之一:如果book节点中show参数的内容为yes,则修改成no */ /** 先用xpath查找对象 */ doc = saxReader.read(new File(filename)); List list = doc.selectNodes("/books/book/@show"); Iterator iter = list.iterator(); while (iter.hasNext()) { Attribute attr = (Attribute) iter.next(); if ("yes".equals(attr.getValue())) { attr.setValue("no"); } } } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } /** 修改内容之二:把owner项内容改为Tshinghua 并在owner节点中加入date节点,date节点的内容为2004-09-11,还为date节点添加一个参数type */ List list = doc.selectNodes("/books/owner"); Iterator iter = list.iterator(); if (iter.hasNext()) { Element ownEle = (Element) iter.next(); ownEle.setText("Tshinghua"); Element dateEle = ownEle.addElement("date"); dateEle.setText("2012-12-17"); dateEle.addAttribute("type", "Gregorian calendar"); } /** 修改内容之三:若title内容为Dom4j Tutorials,则删除该节点 */ List list2 = doc.selectNodes("/books/book"); Iterator iter2 = list2.iterator(); while (iter2.hasNext()) { Element bookEle = (Element) iter2.next(); Iterator iterator = bookEle.elementIterator("title"); while (iterator.hasNext()) { Element titleElement = (Element) iterator.next(); if (titleElement.getText().equals("Dom4j Tutorials")) { bookEle.remove(titleElement); } } } try { /** 将document中的内容写入文件中 */ XMLWriter writer = new XMLWriter(new FileWriter(new File(newfilename))); writer.write(doc); writer.close(); /** 执行成功,需返回1 */ returnValue = 1; } catch (Exception ex) { ex.printStackTrace(); } return returnValue; }
/** * @see * org.springframework.extensions.config.xml.elementreader.ConfigElementReader#parse(org.dom4j.Element) */ @SuppressWarnings("unchecked") public ConfigElement parse(Element element) { DashboardsConfigElement configElement = new DashboardsConfigElement(); if (element != null) { if (DashboardsConfigElement.CONFIG_ELEMENT_ID.equals(element.getName()) == false) { throw new ConfigException( "DashboardsElementReader can only process elements of type 'dashboards'"); } Element layoutsElement = element.element(ELEMENT_LAYOUTS); if (layoutsElement != null) { Iterator<Element> layoutsItr = layoutsElement.elementIterator(ELEMENT_LAYOUT); while (layoutsItr.hasNext()) { LayoutDefinition layoutDef = parseLayoutDefinition(layoutsItr.next()); configElement.addLayoutDefinition(layoutDef); } } Element dashletsElement = element.element(ELEMENT_DASHLETS); if (dashletsElement != null) { Iterator<Element> dashletsItr = dashletsElement.elementIterator(ELEMENT_DASHLET); while (dashletsItr.hasNext()) { DashletDefinition dashletDef = parseDashletDefinition(dashletsItr.next()); configElement.addDashletDefinition(dashletDef); } } Element defaultDashletsElement = element.element(ELEMENT_DEFAULTDASHLETS); if (defaultDashletsElement != null) { Iterator<Element> dashletsItr = defaultDashletsElement.elementIterator(ELEMENT_DASHLET); while (dashletsItr.hasNext()) { String id = getMandatoryDashletAttributeValue(dashletsItr.next(), ATTR_ID); configElement.addDefaultDashlet(id); } } Element guestConfigElement = element.element(ELEMENT_GUESTCONFIG); if (guestConfigElement != null) { boolean allow = Boolean.parseBoolean(guestConfigElement.getTextTrim()); configElement.setAllowGuestConfig(allow); } } return configElement; }