// 修改:属性值,文本 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(); }
/** * 生成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; }
/** * 递归获取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 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; }
/** * 获取 HotelGeo 节点的版本。三个节点:Districts CommericalLocations LandmarkLocations * * @param hotelGeoElement * @return */ public String getHotelGeoVersion(Element hotelGeoElement) { StringBuffer sb = new StringBuffer(""); if (null == hotelGeoElement) { return ""; } List<Element> hgElement = hotelGeoElement.elements(); // 包括 Districts CommericalLocations LandmarkLocations if (null != hgElement && hgElement.size() > 0) { for (int i = 0; i < hgElement.size(); i++) { Element elment = hgElement.get(i); if (null != elment && null != elment.elements()) { for (int j = 0; j < elment.elements().size(); j++) { Element node = (Element) elment.elements().get(j); if (null != node && null != node.attributes()) { for (int a = 0; a < node.attributes().size(); a++) { Attribute att = (Attribute) node.attributes().get(a); sb.append(att.getName()).append(att.getValue()); } } } } } } try { return MD5.encode(sb.toString()); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } return ""; }
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) { // 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(); } }
/** * 修改xml某节点的值 * * @param inputXml 原xml文件 * @param nodes 要修改的节点 * @param attributename 属性名称 * @param value 新值 * @param outXml 输出文件路径及文件名 如果输出文件为null,则默认为原xml文件 */ public static void modifyDocument( File inputXml, String nodes, String attributename, String value, String outXml) { try { SAXReader saxReader = new SAXReader(); Document document = saxReader.read(inputXml); List list = document.selectNodes(nodes); Iterator iter = list.iterator(); while (iter.hasNext()) { Attribute attribute = (Attribute) iter.next(); if (attribute.getName().equals(attributename)) attribute.setValue(value); } XMLWriter output; if (outXml != null) { // 指定输出文件 output = new XMLWriter(new FileWriter(new File(outXml))); } else { // 输出文件为原文件 output = new XMLWriter(new FileWriter(inputXml)); } output.write(document); output.close(); } catch (DocumentException e) { System.out.println(e.getMessage()); } catch (IOException e) { System.out.println(e.getMessage()); } }
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; }
/** * 解析consumer属性值 * * @param Consumer consumer consumer对象 * @param List<Attribute> attrs consumer属性值集合 * @return Consumer */ private Consumer parseAttributes(Consumer consumer, List<Attribute> attrs) { for (Attribute attr : attrs) { String name = attr.getName(); String value = attr.getValue(); consumer = (Consumer) this.callSetterMethodByNameAndValue(consumer, name, value); } return consumer; }
public static List<org.pentaho.ui.xul.dom.Attribute> convertAttributes(List<Attribute> inList) { List<org.pentaho.ui.xul.dom.Attribute> outList = new ArrayList<org.pentaho.ui.xul.dom.Attribute>(); for (Attribute attr : inList) { outList.add(new org.pentaho.ui.xul.dom.Attribute(attr.getName(), attr.getValue())); } return outList; }
/** * 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; }
public String getText() { if (node != null && node instanceof DefaultElement) { if (!hasAttribute()) { return ((DefaultElement) node).getText(); } else { Attribute att = ((DefaultElement) node).attribute(attribute); if (att != null) return att.getValue(); } } return ""; //$NON-NLS-1$ }
/** * Method parseUsingCondition. * * @param element Element * @return Condition */ private Condition parseUsingCondition(Element element) { Condition cond = null; for (Iterator<Attribute> iterator = element.attributeIterator(); iterator.hasNext(); ) { Attribute attribute = iterator.next(); String name = attribute.getName(); String value = attribute.getValue(); if (name.equalsIgnoreCase("slotitem")) { StringTokenizer st = new StringTokenizer(value, ";"); int id = Integer.parseInt(st.nextToken().trim()); int slot = Integer.parseInt(st.nextToken().trim()); int enchant = 0; if (st.hasMoreTokens()) { enchant = Integer.parseInt(st.nextToken().trim()); } cond = joinAnd(cond, new ConditionSlotItemId(slot, id, enchant)); } else if (name.equalsIgnoreCase("kind") || name.equalsIgnoreCase("weapon")) { long mask = 0; StringTokenizer st = new StringTokenizer(value, ","); tokens: while (st.hasMoreTokens()) { String item = st.nextToken().trim(); for (WeaponTemplate.WeaponType wt : WeaponTemplate.WeaponType.VALUES) { if (wt.toString().equalsIgnoreCase(item)) { mask |= wt.mask(); continue tokens; } } for (ArmorTemplate.ArmorType at : ArmorTemplate.ArmorType.VALUES) { if (at.toString().equalsIgnoreCase(item)) { mask |= at.mask(); continue tokens; } } error("Invalid item kind: \"" + item + "\" in " + getCurrentFileName()); } if (mask != 0) { cond = joinAnd(cond, new ConditionUsingItemType(mask)); } } else if (name.equalsIgnoreCase("skill")) { cond = joinAnd(cond, new ConditionUsingSkill(Integer.parseInt(value))); } } return cond; }
@Test public void testValidateHasMultiplePrimaryAttributeNames() { Document document = DocumentHelper.createDocument(); Element element = document.addElement("execute"); element.addAttribute("function", "Click"); element.addAttribute("selenium", "click"); List<String> attributeNames = new ArrayList<>(); List<Attribute> attributes = element.attributes(); for (Attribute attribute : attributes) { attributeNames.add(attribute.getName()); } PoshiRunnerValidation.validateHasMultiplePrimaryAttributeNames( element, attributeNames, Arrays.asList("function", "selenium"), "ValidateHasMultiplePrimaryAttributeNames.macro"); Assert.assertEquals( "validateHasMultiplePrimaryAttributeNames is failing", "", getExceptionMessage()); document = DocumentHelper.createDocument(); element = document.addElement("execute"); element.addAttribute("function", "Click"); element.addAttribute("locator1", "//here"); attributeNames = new ArrayList<>(); attributes = element.attributes(); for (Attribute attribute : attributes) { attributeNames.add(attribute.getName()); } PoshiRunnerValidation.validateHasMultiplePrimaryAttributeNames( element, attributeNames, Arrays.asList("function", "selenium"), "ValidateHasMultiplePrimaryAttributeNames.macro"); Assert.assertEquals( "validateHasMultiplePrimaryAttributeNames is failing", "Too many attributes", getExceptionMessage()); }
// 根据指定的元素创建一个Document @SuppressWarnings("unchecked") private static Document createDocument(Element element) { Document document = DocumentHelper.createDocument(); Element root = document.addElement(element.getName()); List<Attribute> attrs = element.attributes(); // 添加element元素的属性到根元素结点 if (attrs != null) { for (Attribute attr : attrs) { root.addAttribute(attr.getName(), attr.getValue()); } } root.appendContent(element); return document; }
public static Map<String, String> AttributesToMap(List<Attribute> attMap) { Map<String, String> map = new HashMap<String, String>(); for (int i = 0; i < attMap.size(); i++) { Attribute node = attMap.get(i); String name = node.getName(); if (name.equals("ID")) { name = "id"; } map.put(name, node.getValue()); } return map; }
protected void writeAttribute(Attribute attribute) throws IOException { writer.write(" "); writer.write(attribute.getQualifiedName()); writer.write("="); char quote = format.getAttributeQuoteCharacter(); writer.write(quote); writeEscapeAttributeEntities(attribute.getValue()); writer.write(quote); lastOutputNodeType = Node.ATTRIBUTE_NODE; }
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); }
/** * Convert dom4j attributes to SAX attributes. * * @param element dom4j Element * @return SAX Attributes */ public static Attributes getSAXAttributes(Element element) { final AttributesImpl result = new AttributesImpl(); for (Iterator i = element.attributeIterator(); i.hasNext(); ) { final org.dom4j.Attribute attribute = (org.dom4j.Attribute) i.next(); result.addAttribute( attribute.getNamespaceURI(), attribute.getName(), attribute.getQualifiedName(), ContentHandlerHelper.CDATA, attribute.getValue()); } return result; }
/** * 设置系统设置 * * @param setting 系统设置 */ public static void set(Setting setting) { try { File shopxxXmlFile = new ClassPathResource(CommonAttributes.SHOPXX_XML_PATH).getFile(); Document document = new SAXReader().read(shopxxXmlFile); List<Element> elements = document.selectNodes("/shopxx/setting"); for (Element element : elements) { try { String name = element.attributeValue("name"); String value = beanUtils.getProperty(setting, name); Attribute attribute = element.attribute("value"); attribute.setValue(value); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } } FileOutputStream fileOutputStream = null; XMLWriter xmlWriter = null; try { OutputFormat outputFormat = OutputFormat.createPrettyPrint(); outputFormat.setEncoding("UTF-8"); outputFormat.setIndent(true); outputFormat.setIndent(" "); outputFormat.setNewlines(true); fileOutputStream = new FileOutputStream(shopxxXmlFile); xmlWriter = new XMLWriter(fileOutputStream, outputFormat); xmlWriter.write(document); } catch (Exception e) { e.printStackTrace(); } finally { if (xmlWriter != null) { try { xmlWriter.close(); } catch (IOException e) { } } IOUtils.closeQuietly(fileOutputStream); } Ehcache cache = cacheManager.getEhcache(Setting.CACHE_NAME); cache.put(new net.sf.ehcache.Element(Setting.CACHE_KEY, setting)); } catch (Exception e) { e.printStackTrace(); } }
/** * Method parseTargetCondition. * * @param element Element * @return Condition */ private Condition parseTargetCondition(Element element) { Condition cond = null; for (Iterator<Attribute> iterator = element.attributeIterator(); iterator.hasNext(); ) { Attribute attribute = iterator.next(); String name = attribute.getName(); String value = attribute.getValue(); if (name.equalsIgnoreCase("pvp")) { cond = joinAnd(cond, new ConditionTargetPlayable(Boolean.valueOf(value))); } } return cond; }
/** * Method parseZoneCondition. * * @param element Element * @return Condition */ private Condition parseZoneCondition(Element element) { Condition cond = null; for (Iterator<Attribute> iterator = element.attributeIterator(); iterator.hasNext(); ) { Attribute attribute = iterator.next(); String name = attribute.getName(); String value = attribute.getValue(); if (name.equalsIgnoreCase("type")) { cond = joinAnd(cond, new ConditionZoneType(value)); } } return cond; }
/** * @方法功能描述:得到指定节点的所有属性及属性值 @方法名:getNodeAttrMap * * @return 属性集合 @返回类型:Map<String,String> */ public static Map<String, String> getNodeAttrMap(Element e) { Map<String, String> attrMap = new HashMap<String, String>(); if (e == null) { return null; } List<Attribute> attributes = getAttributeList(e); if (attributes == null) { return null; } for (Attribute attribute : attributes) { String attrValueString = attrValue(e, attribute.getName()); attrMap.put(attribute.getName(), attrValueString); } return attrMap; }
private Package parsePackage(Element el) { Package pk = new Package(); Map<String, String> nsMap = new HashMap<String, String>(4); for (Attribute attr : (List<Attribute>) el.attributes()) { String name = attr.getName(); String value = attr.getValue(); if ("name".equals(name)) { pk.setName(value); } else { nsMap.put(name, value); } } pk.setNamespaces(nsMap); pk.setId(pk.getNamespace("js")); parseDoc(el, pk); return pk; }
/** this method is called when the attribute matches the XPath. */ protected void onAttributeMatched(final org.dom4j.Attribute att, Datatype type) { if (com.sun.msv.driver.textui.Debug.debug) System.out.println("field match for " + parent.selector.idConst.localName); final String val = att.getValue(); setValue(val, type); }
/** * 方法名: </br> 详述: </br>修改版本号和package 开发人员:谭明</br> 创建时间:Apr 1, 2014</br> * * @param pageName * @param project_path * @throws Exception */ public static void update_AndroidManifest_xml( String project_path, String enterpriseId, String appId, String appKey) throws Exception { File file = new File(project_path + File.separator + "AndroidManifest.xml"); String pageName = "app" + enterpriseId; String package_value = "com.cndatacom." + pageName; if (!file.exists()) { throw new Exception("项目AndroidManifest.xml文件不存在!"); } Document doc = null; try { doc = new SAXReader().read(file); Element root = doc.getRootElement(); root.setAttributeValue("package", package_value); logger.info("修改后的AndroidManifest.xml文件::" + doc.asXML()); List<Element> elementList = root.element("application").elements("meta-data"); for (Element childElement : elementList) { List<Attribute> aList = childElement.attributes(); String name = ""; Attribute a = null; for (Attribute attribute : aList) { String attributeName = attribute.getName(); if ("value".equals(attributeName)) { a = attribute; } else if ("name".equals(attributeName)) { name = attribute.getValue(); } } childElement.remove(a); if ("app_info".equals(name)) childElement.setAttributeValue("android:value", appId); else if ("app_key".equals(name)) childElement.setAttributeValue("android:value", appKey); } } catch (DocumentException e) { e.printStackTrace(); throw new Exception("读取项目AndroidManifest.xml文件出错!"); } try { XMLWriter writer = new XMLWriter(new FileOutputStream(file)); writer.write(doc); writer.close(); } catch (Exception e) { throw new Exception("输出项目AndroidManifest.xml文件出错!"); } }
/** * Method parsePlayerCondition. * * @param element Element * @return Condition */ private Condition parsePlayerCondition(Element element) { Condition cond = null; for (Iterator<Attribute> iterator = element.attributeIterator(); iterator.hasNext(); ) { Attribute attribute = iterator.next(); String name = attribute.getName(); String value = attribute.getValue(); if (name.equalsIgnoreCase("residence")) { String[] st = value.split(";"); cond = joinAnd( cond, new ConditionPlayerResidence( Integer.parseInt(st[1]), ResidenceType.valueOf(st[0]))); } else if (name.equalsIgnoreCase("classId")) { cond = joinAnd(cond, new ConditionPlayerClassId(value.split(","))); } else if (name.equalsIgnoreCase("olympiad")) { cond = joinAnd(cond, new ConditionPlayerOlympiad(Boolean.valueOf(value))); } else if (name.equalsIgnoreCase("instance_zone")) { cond = joinAnd(cond, new ConditionPlayerInstanceZone(Integer.parseInt(value))); } else if (name.equalsIgnoreCase("race")) { cond = joinAnd(cond, new ConditionPlayerRace(value)); } else if (name.equalsIgnoreCase("damage")) { String[] st = value.split(";"); cond = joinAnd( cond, new ConditionPlayerMinMaxDamage( Double.parseDouble(st[0]), Double.parseDouble(st[1]))); } else if (name.equalsIgnoreCase("castleLight")) { cond = joinAnd(cond, new ConditionCastleLight()); } else if (name.equalsIgnoreCase("castleLightClanLeader")) { cond = joinAnd(cond, new ConditionCastleLightClanLeader()); } else if (name.equalsIgnoreCase("castleDark")) { cond = joinAnd(cond, new ConditionCastleDark()); } else if (name.equalsIgnoreCase("castleDarkClanLeader")) { cond = joinAnd(cond, new ConditionCastleDarkClanLeader()); } } return cond; }
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); } }