public void testWithIntegerArray() throws Exception { this.tag.setPath("someIntegerArray"); Integer[] array = new Integer[50]; for (int i = 0; i < array.length; i++) { array[i] = new Integer(i); } this.tag.setItems(array); int result = this.tag.doStartTag(); assertEquals(Tag.SKIP_BODY, result); String output = getWriter().toString(); output = "<doc>" + output + "</doc>"; SAXReader reader = new SAXReader(); Document document = reader.read(new StringReader(output)); Element rootElement = document.getRootElement(); assertEquals(2, rootElement.elements().size()); Element selectElement = rootElement.element("select"); assertEquals("select", selectElement.getName()); assertEquals("someIntegerArray", selectElement.attribute("name").getValue()); List children = selectElement.elements(); assertEquals("Incorrect number of children", array.length, children.size()); Element e = (Element) selectElement.selectSingleNode("option[text() = '12']"); assertEquals("'12' node not selected", "selected", e.attribute("selected").getValue()); e = (Element) selectElement.selectSingleNode("option[text() = '34']"); assertEquals("'34' node not selected", "selected", e.attribute("selected").getValue()); }
/** 判断站号是否存在,若存在,返回true,不存在,返回false */ private static boolean isZhanHaoExist(String type, HashMap<String, String> map) { String zhanhao = map.get("站号"); if (type.equals("radar")) { List list = doc.selectNodes("root/雷达/模拟器"); Iterator iter = list.iterator(); while (iter.hasNext()) { Element eEle = (Element) iter.next(); if (eEle.attribute("站号").getValue().equals(zhanhao)) { System.out.println("站号" + zhanhao + "已存在"); return true; } } } if (type.equals("esm")) { List list = doc.selectNodes("root/esm/模拟器"); Iterator iter = list.iterator(); while (iter.hasNext()) { Element eEle = (Element) iter.next(); if (eEle.attribute("站号").getValue().equals(zhanhao)) { System.out.println("站号" + zhanhao + "已存在"); return true; } } } return false; }
public void testWithMultiMap() throws Exception { Map someMap = new HashMap(); someMap.put("M", "Male"); someMap.put("F", "Female"); this.bean.setSomeMap(someMap); this.tag.setPath("someMap"); this.tag.setItems("${sexes}"); int result = this.tag.doStartTag(); assertEquals(Tag.SKIP_BODY, result); String output = getWriter().toString(); output = "<doc>" + output + "</doc>"; SAXReader reader = new SAXReader(); Document document = reader.read(new StringReader(output)); Element rootElement = document.getRootElement(); assertEquals(2, rootElement.elements().size()); Element selectElement = rootElement.element("select"); assertEquals("select", selectElement.getName()); assertEquals("someMap", selectElement.attribute("name").getValue()); List children = selectElement.elements(); assertEquals("Incorrect number of children", 2, children.size()); String hdivValue = this.confidentiality ? "1" : "M"; Element e = (Element) selectElement.selectSingleNode("option[@value = '" + hdivValue + "']"); assertEquals("M node not selected", "selected", e.attribute("selected").getValue()); hdivValue = this.confidentiality ? "2" : "F"; e = (Element) selectElement.selectSingleNode("option[@value = '" + hdivValue + "']"); assertEquals("F node not selected", "selected", e.attribute("selected").getValue()); }
public void testWithMultiList() throws Exception { List list = new ArrayList(); list.add(Country.COUNTRY_UK); list.add(Country.COUNTRY_AT); this.bean.setSomeList(list); this.tag.setPath("someList"); this.tag.setItems("${countries}"); this.tag.setItemValue("isoCode"); int result = this.tag.doStartTag(); assertEquals(Tag.SKIP_BODY, result); String output = getWriter().toString(); output = "<doc>" + output + "</doc>"; SAXReader reader = new SAXReader(); Document document = reader.read(new StringReader(output)); Element rootElement = document.getRootElement(); assertEquals(2, rootElement.elements().size()); Element selectElement = rootElement.element("select"); assertEquals("select", selectElement.getName()); assertEquals("someList", selectElement.attribute("name").getValue()); List children = selectElement.elements(); assertEquals("Incorrect number of children", 4, children.size()); String hdivValue = this.confidentiality ? "3" : "UK"; Element e = (Element) selectElement.selectSingleNode("option[@value = '" + hdivValue + "']"); assertEquals("UK node not selected", "selected", e.attribute("selected").getValue()); hdivValue = this.confidentiality ? "1" : "AT"; e = (Element) selectElement.selectSingleNode("option[@value = '" + hdivValue + "']"); assertEquals("AT node not selected", "selected", e.attribute("selected").getValue()); }
public static String setGraphXml(String sourceNode, Map<String, String> map, String xml) throws IOException { Document doc = Dom4jUtil.loadXml(xml); Element root = doc.getRootElement(); Element node = (Element) root.selectSingleNode("//bg:Gateway[@id='" + sourceNode + "']"); Element portsEl = node.element("ports"); List portList = portsEl.elements(); for (int i = 0; i < portList.size(); i++) { Element portEl = (Element) portList.get(i); if ((portEl.attribute("x") != null) || (portEl.attribute("y") != null)) { String id = portEl.attributeValue("id"); Element outNode = (Element) root.selectSingleNode("//bg:SequenceFlow[@startPort='" + id + "']"); if (outNode != null) { String outPort = outNode.attributeValue("endPort"); Element tmpNode = (Element) root.selectSingleNode("//ciied:Port[@id='" + outPort + "']"); Element taskNode = tmpNode.getParent().getParent(); String taskId = taskNode.attributeValue("id"); Element conditionEl = outNode.element("condition"); if (conditionEl != null) { outNode.remove(conditionEl); } if (map.containsKey(taskId)) { String condition = (String) map.get(taskId); Element elAdd = outNode.addElement("condition"); elAdd.addText(condition); } } } } return doc.asXML(); }
public void testMultiWithEmptyCollection() throws Exception { this.bean.setSomeList(new ArrayList()); this.tag.setPath("someList"); this.tag.setItems("${countries}"); this.tag.setItemValue("isoCode"); int result = this.tag.doStartTag(); assertEquals(Tag.SKIP_BODY, result); String output = getWriter().toString(); output = "<doc>" + output + "</doc>"; SAXReader reader = new SAXReader(); Document document = reader.read(new StringReader(output)); Element rootElement = document.getRootElement(); assertEquals(2, rootElement.elements().size()); Element selectElement = rootElement.element("select"); assertEquals("select", selectElement.getName()); assertEquals("someList", selectElement.attribute("name").getValue()); assertEquals("multiple", selectElement.attribute("multiple").getValue()); List children = selectElement.elements(); assertEquals("Incorrect number of children", 4, children.size()); Element inputElement = rootElement.element("input"); assertNotNull(inputElement); }
public void testWithCollection() throws Exception { getPageContext() .setAttribute( SelectTag.LIST_VALUE_PAGE_ATTRIBUTE, new BindStatus(getRequestContext(), "testBean.country", false)); this.tag.setItems("${countries}"); this.tag.setItemValue("isoCode"); this.tag.setItemLabel("name"); this.tag.setId("myOption"); this.tag.setCssClass("myClass"); this.tag.setOnclick("CLICK"); int result = this.tag.doStartTag(); assertEquals(Tag.SKIP_BODY, result); String output = getOutput(); output = "<doc>" + output + "</doc>"; SAXReader reader = new SAXReader(); Document document = reader.read(new StringReader(output)); Element rootElement = document.getRootElement(); List children = rootElement.elements(); assertEquals("Incorrect number of children", 4, children.size()); Element element = (Element) rootElement.selectSingleNode("option[@value = 'UK']"); assertEquals("UK node not selected", "selected", element.attribute("selected").getValue()); assertEquals("myOption3", element.attribute("id").getValue()); assertEquals("myClass", element.attribute("class").getValue()); assertEquals("CLICK", element.attribute("onclick").getValue()); }
public void testHiddenElementOmittedOnDisabled() throws Exception { this.tag.setPath("stringArray"); this.tag.setItems(new Object[] {"foo", "bar", "baz"}); this.tag.setDisabled("true"); int result = this.tag.doStartTag(); assertEquals(Tag.SKIP_BODY, result); String output = getOutput(); // wrap the output so it is valid XML output = "<doc>" + output + "</doc>"; SAXReader reader = new SAXReader(); Document document = reader.read(new StringReader(output)); Element rootElement = document.getRootElement(); assertEquals( "Both tag and hidden element rendered incorrectly", 3, rootElement.elements().size()); Element spanElement = (Element) document.getRootElement().elements().get(0); Element checkboxElement = (Element) spanElement.elements().get(0); assertEquals("input", checkboxElement.getName()); assertEquals("checkbox", checkboxElement.attribute("type").getValue()); assertEquals("stringArray", checkboxElement.attribute("name").getValue()); assertEquals("checked", checkboxElement.attribute("checked").getValue()); assertEquals("disabled", checkboxElement.attribute("disabled").getValue()); assertEquals("foo", checkboxElement.attribute("value").getValue()); }
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; } }
/** Adds the test to the suite report given an XML test document */ public void addTest(Document test) { Element root = test.getRootElement(); // Add to the number of tests in this suite if not seen and not null String testMethod = root.attributeValue(NAME_ATTRIBUTE); if (!recordedRuns.contains(testMethod) && !testMethod.equals("null")) { recordedRuns.add(testMethod); suite.addTest(); } // add test time to total time long time = Long.parseLong(root.attributeValue(TIME_ATTRIBUTE)); suite.addTime(time); root.attribute(TIME_ATTRIBUTE).setText(formatTime(time)); // If the test method name is null, then make it the classname if (root.attributeValue(NAME_ATTRIBUTE).equals("null")) { root.attribute(NAME_ATTRIBUTE).setText(root.attributeValue(CLASSNAME_ATTRIBUTE)); } // Add the test to the report document document.getRootElement().add(root); // Check for special status adjustments to make to suite checkForStatus(test); // remove status attribute since it's only used by the report root.remove(root.attribute(STATUS_ATTRIBUTE)); }
/** * 递归获取layout中全部控件 * * @param layoutXml 布局文件的绝对路径,如xxx/res/layout/main.xml * @param include 是否将include引用的布局中内容也获取到 */ public static void parseElementFromXml(String layoutXml, boolean include) { Document document = XmlUtil.read(layoutXml); List<Element> docElements = XmlUtil.getAllElements(document); // 将view名称和对应的id名封装为一个实体类,并存至集合中 for (Element element : docElements) { Attribute attrID = element.attribute("id"); // 如果包含include并且需要获取其中内容则进行递归获取 if (element.getName().equals("include") && include) { Attribute attribute = element.attribute("layout"); // 原布局路径和include中的布局拼成新的路径 String includeLayoutXml = layoutXml.substring(0, layoutXml.lastIndexOf("\\") + 1) + attribute.getValue().substring(attribute.getValue().indexOf("/") + 1) + ".xml"; // 继续递归获取include的布局中控件 parseElementFromXml(includeLayoutXml, include); } // 保存有id的控件信息 if (attrID != null) { String value = attrID.getValue(); String idName = value.substring(value.indexOf("/") + 1); IdNamingBean bean = new IdNamingBean(element.getName(), idName, element); if (!idNamingBeans.contains(bean)) { idNamingBeans.add(bean); } } } }
/** 测试方法 */ public static void TestGetNodeList(String rmiName) { List nodeList = new ArrayList(); Document doc = FileUtil.loadXml("E:\\tsms\\defaultroot\\WEB-INF\\rmi-config.xml"); List nodes = doc.selectNodes("//rmi-config/listeners/listener/node"); Iterator it = nodes.iterator(); // System.out.println("nodes:" + nodes); while (it.hasNext()) { Element elm = (Element) it.next(); if (rmiName.equals(elm.attribute("rmiName").getValue())) { RMINode rminode = new RMINode(); rminode.setHost(elm.attribute("host").getValue()); rminode.setPort(Integer.parseInt(elm.attribute("port").getValue())); rminode.setRmiName(rmiName); nodeList.add(rminode); } } for (int i = 0; i < nodeList.size(); i++) { RMINode node = (RMINode) nodeList.get(i); System.out.println(node.getHost()); System.out.println(node.getPort()); } RMINode node0 = (RMINode) nodeList.get(0); System.out.println("----node0----"); System.out.println(node0.getHost()); System.out.println(node0.getPort()); }
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; }
/** * Reads a post signer request off the wire, sends it to the WS with a new callback for returning * the response. * * @param request the post signer request * @param responseCallback the callback to send the response back */ void processPostSignerRequest(final IQ request, final PacketCallback responseCallback) { Element item = null, signatureElement = null; Element pubsubRequest = request.getElement().element("pubsub"); Element publish = pubsubRequest.element("publish"); if (publish != null) { item = publish.element("item"); if (item != null) { signatureElement = item.element("signature"); } } if (publish == null || item == null || signatureElement == null || signatureElement.attribute("domain") == null || signatureElement.attribute("algorithm") == null || signatureElement.element("certificate") == null) { responseCallback.error(FederationErrors.badRequest("Malformed post signer request")); return; } ProtocolSignerInfo signer; try { signer = XmppUtil.xmlToProtocolSignerInfo(signatureElement); } catch (UnknownSignerType e) { responseCallback.error( FederationErrors.badRequest("Could not understand signer algorithm: " + e)); return; } WaveletFederationProvider.PostSignerInfoResponseListener listener = new WaveletFederationProvider.PostSignerInfoResponseListener() { @Override public void onFailure(FederationError error) { responseCallback.error(error); } @Override public void onSuccess() { IQ response = IQ.createResultIQ(request); Element pubsub = response.setChildElement("pubsub", XmppNamespace.NAMESPACE_PUBSUB); Element item = pubsub.addElement("publish").addElement("item"); item.addAttribute("node", "signer"); item.addElement("signature-response", XmppNamespace.NAMESPACE_WAVE_SERVER); responseCallback.run(response); } }; // TODO(thorogood,arb): This field is a Bad Idea; it could be faked and not // be a provider we host on this instance. Instead, we should infer from the // "To:" JID. String targetDomain = signatureElement.attributeValue("domain"); // The first argument is the domain we intend to send this information to. waveletProvider.postSignerInfo(targetDomain, signer, listener); }
public void clickLongOnElem(Element elem) { int x = Integer.parseInt(elem.attribute("x").getValue()); int y = Integer.parseInt(elem.attribute("y").getValue()); int w = Integer.parseInt(elem.attribute("w").getValue()); int h = Integer.parseInt(elem.attribute("h").getValue()); this.clickLongOnScreen(x + w / 2, y + h / 2); }
public static DownloadablePackageOptions parsePackages(InputStream in) { DownloadablePackageOptions options = new DownloadablePackageOptions(); List<DownloadPackage> pkgs = new ArrayList<DownloadPackage>(); Document document = parse(in); if (document != null) { String baseUrl = document.getRootElement().element("packageDefinitions").attributeValue("baseUrl"); // parse package definition for (Object el : document.getRootElement().element("packageDefinitions").elements("package")) { DownloadPackage pkg = readPackageDefinition((Element) el, baseUrl); if (pkg != null) { pkgs.add(pkg); } } options.setAllPackages(pkgs); Element install = document.getRootElement().element("install"); // get common packages if (install.element("common") != null) { for (Object el : install.element("common").elements("package")) { DownloadPackage pkg = readCommonPackage((Element) el, pkgs); if (pkg != null) { options.addCommonPackage(pkg); } } } nodeCounter = 0; // get package Options for (Object el : install.element("packageOptions").elements("package")) { DownloadablePackageOption pkg = readPackageOptions((Element) el, pkgs); if (pkg != null) { options.addOptions(pkg); } } // get presets if (document.getRootElement().element("presets") != null) { for (Object el : document.getRootElement().element("presets").elements("preset")) { Element preset = (Element) el; String presetId = preset.attribute("id").getValue(); String presetLabel = preset.attribute("label").getValue(); String pkgList = preset.getText(); String[] presetPackages = pkgList.split(","); options.addPreset(presetId, presetLabel, presetPackages); } } } return options; }
public Map<Long, WeiboData> gexfDecoder(Resources res, String Filename) { SAXReader saxReader = new SAXReader(); Document document = null; Map<Long, WeiboData> map = new HashMap<Long, WeiboData>(); try { InputStream inpt_strm = res.getAssets().open(Filename); document = saxReader.read(inpt_strm); } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } Element root = document.getRootElement(); Element graph = (Element) root.element("graph"); List<Element> nodes = graph.element("nodes").elements("node"); List<Element> edges = graph.element("edges").elements("edge"); // 读取节点信息 for (int i = 0; i < nodes.size(); i++) { Element node = nodes.get(i); // String sss = node.attribute("id").getText(); long id = Long.parseLong(node.attribute("id").getText()); String label = node.attribute("label").getText(); List<Element> viz = node.content(); Element color = viz.get(0); int color_b = Integer.parseInt(color.attribute("b").getText()); int color_g = Integer.parseInt(color.attribute("g").getText()); int color_r = Integer.parseInt(color.attribute("r").getText()); int color_int = Color.argb(255, color_r, color_g, color_b); Element position = viz.get(1); float x = Float.parseFloat(position.attribute("x").getText()); float y = Float.parseFloat(position.attribute("y").getText()); float z = Float.parseFloat(position.attribute("z").getText()); Element size = viz.get(2); float value = Float.parseFloat(size.attribute("value").getText()); Element image = viz.get(3); String imageURI = image.attribute("uri").getText(); System.out.println(label); WeiboData weibodata = new WeiboData(x, y, z, label, id, color_int, value, imageURI); map.put(id, weibodata); } for (int i = 0; i < edges.size(); i++) { Element edge = edges.get(i); long source_id = Long.parseLong(edge.attribute("source").getText()); long target_id = Long.parseLong(edge.attribute("target").getText()); WeiboData source = map.get(source_id); WeiboData target = map.get(target_id); if (source.parent == null) // 即还没有找到母节点 { source.parent = target; target.childs.add(source); } else { target.parent = source; source.childs.add(target); } } return map; }
/** * 遍历整个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(); } }
private void addGlobalValueForMap(Element e, Map map) { String name = ""; String value = ""; Attribute e_name = e.attribute("name"); if (e_name != null) { name = e_name.getText(); } Attribute e_value = e.attribute("value"); if (e_value != null) { value = e_value.getText(); } map.put(name, value); }
@SuppressWarnings("deprecation") private static void modNode(String qbPath, String type, HashMap<String, String> map) { leidaEle = doc.getRootElement().element("雷达"); esmEle = doc.getRootElement().element("esm"); String zhanhao = map.get("站号"); if (type.equals("radar")) { boolean flag = isZhanHaoExist(type, map); if (!flag) { System.out.println("修改节点失败"); return; } List list = doc.selectNodes("root/雷达/模拟器"); Iterator iter = list.iterator(); while (iter.hasNext()) { Element modEle = (Element) iter.next(); if (modEle.attribute("站号").getValue().equals(zhanhao)) { modEle.element("位置").setAttributeValue("经度", map.get("经度")); modEle.element("位置").setAttributeValue("纬度", map.get("纬度")); modEle.element("位置").setAttributeValue("高度", map.get("高度")); modEle.element("情报格式").setAttributeValue("格式", map.get("格式")); modEle.element("传输协议").setAttributeValue("协议", map.get("协议")); modEle.element("目的IP").setAttributeValue("地址", map.get("地址")); } } writeXml(doc, qbPath); } if (type.equals("esm")) { boolean flag = isZhanHaoExist("esm", map); if (!flag) { System.out.println("修改节点失败"); return; } List list = doc.selectNodes("root/esm/模拟器"); Iterator iter = list.iterator(); while (iter.hasNext()) { Element modEle = (Element) iter.next(); if (modEle.attribute("站号").getValue().equals(zhanhao)) { modEle.element("位置").setAttributeValue("经度", map.get("经度")); modEle.element("位置").setAttributeValue("纬度", map.get("纬度")); modEle.element("位置").setAttributeValue("高度", map.get("高度")); modEle.element("情报格式").setAttributeValue("格式", map.get("格式")); modEle.element("传输协议").setAttributeValue("协议", map.get("协议")); modEle.element("目的IP").setAttributeValue("地址", map.get("地址")); } } writeXml(doc, qbPath); } System.out.println("成功修改" + type + " 站号为 " + zhanhao + " 的模拟器"); }
/** * @方法功能描述: 得到指定节点的指定属性 @方法名:getAttribute * * @param element 指定的元素 * @param attrName 属性名称 * @return Attribute @返回类型:Attribute */ public static Attribute getAttribute(Element element, String attrName) { attrName = attrName.trim(); if (element == null) return null; if (attrName == null || attrName.equals("")) return null; Attribute attribute = element.attribute(attrName); return attribute; }
public void processDiscoItemsResponse(JID from, List<Element> items) throws ComponentException { for (Element item : items) { Attribute name = item.attribute("name"); if (name != null && name.getStringValue().equals(BUDDYCLOUD_SERVER)) { remoteChannelDiscoveryStatus.put(from.toString(), DISCOVERED); setDiscoveredServer(from.toString(), item.attributeValue("jid")); sendFederatedRequests(from.toString()); return; } } IQ infoRequest = new IQ(IQ.Type.get); infoRequest.setFrom(localServer); infoRequest.getElement().addElement("query", JabberPubsub.NS_DISCO_INFO); remoteServerItemsToProcess.put(from.toString(), items.size()); String infoRequestId; for (Element item : items) { infoRequestId = getId() + ":info"; infoRequest.setTo(item.attributeValue("jid")); infoRequest.setID(infoRequestId); remoteServerInfoRequestIds.put(infoRequestId, from.toString()); component.sendPacket(infoRequest.createCopy()); } remoteChannelDiscoveryStatus.put(from.toString(), DISCO_INFO); }
// 修改:属性值,文本 public static void main(String[] args) throws Exception { Document doc = new SAXReader().read(new File("C:/Users/Administrator/Desktop/contact.xml")); // 方案一: 修改属性值 1.得到标签对象 2.得到属性对象 3.修改属性值 // 1.1 得到标签对象 Element contactElem = doc.getRootElement().element("contact"); // 1.2 得到属性对象 Attribute idAttr = contactElem.attribute("id"); // 1.3 修改属性值 idAttr.setValue("003"); // 方案二: 修改属性值 // 1.1 得到标签对象 Element contactElem1 = doc.getRootElement().element("contact"); // 1.2 通过增加同名属性的方法,修改属性值 contactElem.addAttribute("id", "004"); // 修改文本 1.得到标签对象 2.修改文本 Element nameElem = doc.getRootElement().element("contact").element("name"); nameElem.setText("demo7"); FileOutputStream out = new FileOutputStream("C:/Users/Administrator/Desktop/test/contact.xml"); OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding("utf-8"); XMLWriter writer = new XMLWriter(out, format); writer.write(doc); writer.close(); }
protected static DownloadPackage readPackageDefinition(Element el, String baseUrl) { String id = el.attribute("id").getValue(); if (id != null) { DownloadPackage pkg = new DownloadPackage(id); String bUrl = el.attributeValue("baseUrl"); if (bUrl == null) { bUrl = baseUrl; } pkg.setLabel(el.attributeValue("label")); pkg.setFilename(el.attributeValue("filename")); pkg.setMd5(el.attributeValue("md5")); pkg.setBaseUrl(bUrl); pkg.setColor(el.attributeValue("color")); pkg.setTextColor(el.attributeValue("textcolor")); pkg.setShortLabel(el.attributeValue("shortlabel")); String url = el.attributeValue("url"); if (url != null) { pkg.setDownloadUrl(url); } String implies = el.attributeValue("implies"); if (implies != null && !implies.trim().equals("")) { String[] deps = implies.split(","); pkg.addDeps(deps); } return pkg; } return null; }
// 解析价格跟踪 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; }
/** * 生成sel的document * * @param normalName normal普通状态的图片名 * @param specialName 特殊状态(pressed按下/checked选中)的图片名 * @param end 特殊状态(pressed按下/checked选中)后缀名 * @return */ public static Document createSelector(String normalName, String specialName, String end) { Document doc = XmlUtil.read("res\\drawable\\sel.xml"); Element rootElement = doc.getRootElement(); List<Element> elements = XmlUtil.getAllElements(doc); for (Element element : elements) { Attribute attr = element.attribute("drawable"); if (attr == null) { continue; } String value = attr.getStringValue(); if (value.contains(end)) { // 替换特殊状态(pressed/checked)的item加后缀 value = value.replace(end, specialName); attr.setValue(value); } else if (element.attributeCount() > 1) { // 移除不需要的element rootElement.remove(element); } else { // normal状态的item不加后缀 value = value.replace("normal", normalName); attr.setValue(value); } } return doc; }
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; }
/** * 获取远程方法调用节点 * * @param String rmiName * @return List<RMINode> nodeList */ public static List<RMINode> getRMINodeList(String rmiName) { List<RMINode> nodelist = new ArrayList<RMINode>(); Document doc = getConfigDoc(); List nodes = doc.selectNodes("//rmi-config/listeners/listener/node"); Iterator it = nodes.iterator(); while (it.hasNext()) { Element elm = (Element) it.next(); if (rmiName.equals(elm.attribute("rmiName").getValue())) { RMINode rminode = new RMINode(); rminode.setHost(elm.attribute("host").getValue()); rminode.setPort(Integer.parseInt(elm.attribute("port").getValue())); rminode.setRmiName(rmiName); nodelist.add(rminode); } } return nodelist; }
/** * Determines if element is a special case of XML elements where it contains an xml:space * attribute of "preserve". If it does, then retain whitespace. * * @param element DOCUMENT ME! * @return DOCUMENT ME! */ protected final boolean isElementSpacePreserved(Element element) { final Attribute attr = (Attribute) element.attribute("space"); boolean preserveFound = preserve; // default to global state if (attr != null) { preserveFound = "xml".equals(attr.getNamespacePrefix()) && "preserve".equals(attr.getText()); } return preserveFound; }
private void validateOutput(String output, boolean selected) throws DocumentException { SAXReader reader = new SAXReader(); Document document = reader.read(new StringReader(output)); Element rootElement = document.getRootElement(); assertEquals("select", rootElement.getName()); assertEquals("country", rootElement.attribute("name").getValue()); List children = rootElement.elements(); assertEquals("Incorrect number of children", 4, children.size()); String hdivValue = this.confidentiality ? "3" : "UK"; Element e = (Element) rootElement.selectSingleNode("option[@value = '" + hdivValue + "']"); Attribute selectedAttr = e.attribute("selected"); if (selected) { assertTrue(selectedAttr != null && "selected".equals(selectedAttr.getValue())); } else { assertNull(selectedAttr); } }