List of usage examples for org.dom4j Element nodeIterator
Iterator<Node> nodeIterator();
From source file:com.beetle.framework.persistence.access.DBConfig.java
License:Apache License
public static List<String> getAllDatasourcename() { Document doc = null;// w w w. ja v a 2s .c om try { List<String> myList = new ArrayList<String>(); doc = XMLReader.getXmlDoc(AppProperties.getAppHome() + "DBConfig.xml"); Element root = doc.getRootElement(); for (Iterator<?> i = root.elementIterator("DataSources"); i.hasNext();) { Element e = (Element) i.next(); @SuppressWarnings("unchecked") Iterator<Node> n = e.nodeIterator(); while (n.hasNext()) { Node at = n.next(); if (at.getName() != null) { myList.add(at.getName()); } } } return myList; } catch (Exception e) { throw new AppRuntimeException(e); } finally { if (doc != null) { doc.clearContent(); } } }
From source file:com.christophermrossi.jpt.PageTemplateImpl.java
License:Open Source License
private void defaultContent(Element element, ContentHandler contentHandler, LexicalHandler lexicalHandler, Interpreter beanShell, Stack slotStack) throws SAXException, PageTemplateException, IOException { // Use default template content for (Iterator i = element.nodeIterator(); i.hasNext();) { Node node = (Node) i.next(); switch (node.getNodeType()) { case Node.ELEMENT_NODE: processElement((Element) node, contentHandler, lexicalHandler, beanShell, slotStack); break; case Node.TEXT_NODE: char[] text = node.getText().toCharArray(); contentHandler.characters(text, 0, text.length); break; case Node.COMMENT_NODE: char[] comment = node.getText().toCharArray(); lexicalHandler.comment(comment, 0, comment.length); break; case Node.CDATA_SECTION_NODE: lexicalHandler.startCDATA(); char[] cdata = node.getText().toCharArray(); contentHandler.characters(cdata, 0, cdata.length); lexicalHandler.endCDATA();//from w w w.ja v a2 s . c o m break; case Node.NAMESPACE_NODE: Namespace declared = (Namespace) node; //System.err.println( "Declared namespace: " + declared.getPrefix() + ":" + declared.getURI() ); namespaces.put(declared.getPrefix(), declared.getURI()); //if ( declared.getURI().equals( TAL_NAMESPACE_URI ) ) { // this.talNamespacePrefix = declared.getPrefix(); //} //else if (declared.getURI().equals( METAL_NAMESPACE_URI ) ) { // this.metalNamespacePrefix = declared.getPrefix(); //} break; case Node.ATTRIBUTE_NODE: // Already handled break; case Node.DOCUMENT_TYPE_NODE: case Node.ENTITY_REFERENCE_NODE: case Node.PROCESSING_INSTRUCTION_NODE: default: //System.err.println( "WARNING: Node type not supported: " + node.getNodeTypeName() ); } } }
From source file:com.devoteam.srit.xmlloader.core.utils.XMLElementTextOnlyParser.java
License:Open Source License
public List<Element> replace(Element element, ParameterPool variables) throws Exception { List<Element> result = new LinkedList(); result.add(element.createCopy());// w w w.j a v a 2 s. c o m element = result.get(0); Iterator nodesIterator = element.nodeIterator(); HashMap<Node, Node> nodesToReplace = new HashMap<Node, Node>(); boolean alreadyNext = false; while (nodesIterator.hasNext()) { Node node = null; if (!alreadyNext) { node = (Node) nodesIterator.next(); } Node lastTextNode = null; String lastTextNodeText = ""; alreadyNext = false; // // We put all successive TEXT Nodes into one node ( there is some fragmentation i don't understand ) // while (null != node && node.getNodeType() == Node.TEXT_NODE) { alreadyNext = true; lastTextNode = (Text) node; lastTextNodeText += lastTextNode.getText(); // this node will be deleted later ... if not overwritten in this hashmap nodesToReplace.put(lastTextNode, null); if (nodesIterator.hasNext()) { node = (Node) nodesIterator.next(); } else { node = null; } } // // We process normally the CDATA Nodes // if (null != node && node.getNodeType() == Node.CDATA_SECTION_NODE) { lastTextNode = (Node) node; lastTextNodeText = lastTextNode.getText(); } // // We do nothing for the other type Nodes // if (null == lastTextNode) { continue; } lastTextNode.setText(lastTextNodeText); // // Now that we have only one, complete, TEXT node or one CDATA node to proceed // Node textNode = (Node) lastTextNode; String text = textNode.getText(); String out = ""; int endOfLine; String line; // // Transform all \r\n, in \n // //text = Utils.replaceNoRegex(text, "\r", ""); while (text.length() > 0) { // // Read a line // endOfLine = text.indexOf("\n"); if (endOfLine == -1) { line = text; text = ""; } else { line = text.substring(0, endOfLine + 1); text = text.substring(endOfLine + 1); } // // Replace line if it contains at least a variable // if (Parameter.containsParameter(line)) { List<String> results = variables.parse(line); for (String s : results) { out += s; } } else { out += line; } } // // Set new text into new AVP // Text newTextNode = new DefaultText(out); nodesToReplace.put(textNode, newTextNode); } for (Node key : nodesToReplace.keySet()) { DefaultElementInterface.replaceNode((DefaultElement) element, key, nodesToReplace.get(key)); } if (result.size() != 1) { throw new ExecutionException("Size of result for XMLElementTextOnlyParser should be 1"); } return result; }
From source file:com.globalsight.connector.mindtouch.util.MindTouchHelper.java
License:Apache License
/** * Parse tree xml from "getTreeXml(pageId)" method to form a tree. * // w ww . ja va 2 s . c o m * @param treeXml * -- the tree information in XML format. * @return MindTouchPage */ @SuppressWarnings("rawtypes") public MindTouchPage parseTreeXml(String treeXml) throws Exception { MindTouchPage rootMtp = null; Document doc = getDocument(treeXml); String id = null; String href = null; List pageNodes = doc.selectNodes("//page"); List<MindTouchPage> allPages = new ArrayList<MindTouchPage>(); Iterator it = pageNodes.iterator(); while (it.hasNext()) { MindTouchPage mtp = new MindTouchPage(); Element pageNode = (Element) it.next(); // page id id = pageNode.attributeValue("id"); mtp.setId(Long.parseLong(id)); // href href = pageNode.attributeValue("href"); mtp.setHref(href); // parent page id String parentName = null; if (pageNode.getParent() != null) { parentName = pageNode.getParent().getName(); } if ("subpages".equals(parentName)) { String parentId = pageNode.getParent().getParent().attributeValue("id"); mtp.setParentId(Long.parseLong(parentId)); } else if ("pages".equals(parentName)) { rootMtp = mtp; } Iterator subNodeIt = pageNode.nodeIterator(); while (subNodeIt.hasNext()) { Element node = (Element) subNodeIt.next(); String name = node.getName(); String text = node.getText(); if ("uri.ui".equals(name)) { mtp.setUriUi(text); } else if ("title".equals(name)) { // title cannot have "<" and ">" text = text.replace("<", "<").replace(">", ">"); // as json does not allow "\" and "/", remove them for displaying. text = text.replace("\\", "").replace("/", ""); text = text.replace("%22", "\""); text = text.replace("%3F", "?"); text = text.replace("%23", "#"); text = text.replace("%3D", "="); text = text.replace("%26", "&"); text = text.replace("%25", "%"); mtp.setTitle(text); } else if ("path".equals(name)) { mtp.setPath(text); } else if ("date.created".equals(name)) { mtp.setDateCreated(text); } } allPages.add(mtp); } HashMap<Long, MindTouchPage> map = new HashMap<Long, MindTouchPage>(); for (MindTouchPage mtp : allPages) { map.put(mtp.getId(), mtp); } for (MindTouchPage mtp : allPages) { long parentId = mtp.getParentId(); MindTouchPage parent = map.get(parentId); if (parent != null) { parent.addSubPage(mtp); } } return rootMtp; }
From source file:com.globalsight.connector.mindtouch.util.MindTouchHelper.java
License:Apache License
/** * Parse page info xml from "getPageInfo()" method. * //from ww w.j ava 2 s. co m * @param pageInfoXml * @return MindTouchPage * @throws DocumentException */ @SuppressWarnings("rawtypes") public MindTouchPage parsePageInfoXml(String pageInfoXml) throws DocumentException { MindTouchPage mtp = new MindTouchPage(); Document doc = getDocument(pageInfoXml); String id = null; String href = null; List pageNodes = doc.selectNodes("//page"); if (pageNodes != null && pageNodes.size() > 0) { Element pageNode = (Element) pageNodes.get(0); // page id id = pageNode.attributeValue("id"); mtp.setId(Long.parseLong(id)); // href href = pageNode.attributeValue("href"); mtp.setHref(href); String name = null; String text = null; Iterator subNodeIt = pageNode.nodeIterator(); while (subNodeIt.hasNext()) { Element node = (Element) subNodeIt.next(); name = node.getName(); text = node.getText(); if ("uri.ui".equals(name)) { mtp.setUriUi(text); } else if ("title".equals(name)) { mtp.setTitle(text); } else if ("path".equals(name)) { mtp.setPath(text); } else if ("date.created".equals(name)) { mtp.setDateCreated(text); } } } return mtp; }
From source file:com.globalsight.everest.edit.offline.ttx.TTXParser.java
License:Apache License
/** * Parse offline uploading TTX file for uploading purpose. * /*w w w. jav a 2 s . c om*/ * @param doc * @param isParsingTTXForGS * :True for GS uploading;False for common TTX file parsing. * @return * @throws Exception */ public String parseToTxt(Document doc, boolean isParsingTTXForGS) throws Exception { this.isParsingTTXForGS = isParsingTTXForGS; Element root = doc.getRootElement();// TRADOStag element // toolSettings parseToolSettings(root); // userSettings parseUserSettings(root); Element bodyElement = root.element(TTXConstants.BODY); Element rawElement = bodyElement.element(TTXConstants.RAW); // parse header info such as "pageId","taskId" etc. parseHeaderInfo(rawElement); // append header info appendHeaderInfo(); // main contents if (rawElement.nodeCount() > 0) { Iterator nodesIt = rawElement.nodeIterator(); while (nodesIt.hasNext()) { Node node = (Node) nodesIt.next(); String nodeStr = node.asXML(); domNodehandler(node, false); } } appendEndInfo(); return results.toString(); }
From source file:com.globalsight.everest.edit.offline.ttx.TTXParser.java
License:Apache License
private void elementNodeProcessor(Node p_node, boolean p_isSource) { Element element = (Element) p_node; String eleStr = element.asXML(); String elementName = element.getName(); boolean isHeaderInfoUT = false; boolean isTuId = false; if (TTXConstants.TU.equalsIgnoreCase(elementName) || (element.getParent() != null && TTXConstants.TUV.equalsIgnoreCase(element.getParent().getName()))) { // latestPosition = TTXConstants.IN_TU; } else if (TTXConstants.UT.equalsIgnoreCase(elementName)) { Attribute att = element.attribute(TTXConstants.UT_ATT_DISPLAYTEXT); if (att != null) { String value = att.getValue(); // If header info,return as header info has been handled // separately. // This check is not required. isHeaderInfoUT = isHeaderInfo(value); if (isHeaderInfoUT) { return; }/* w w w . j a v a 2s.c o m*/ // If TuId,handle them here. isTuId = isTuId(value); if (isTuId) { // latestPosition = TTXConstants.TU_ID; String tuId = value.substring(value.indexOf(":") + 1).trim(); if (results != null && results.length() > 0) { results.append(TTXConstants.NEW_LINE).append(TTXConstants.NEW_LINE); } results.append(TTXConstants.HASH_MARK).append(tuId).append(TTXConstants.NEW_LINE); return; } } } if (element.nodeCount() > 0) { Iterator nodesIt = element.nodeIterator(); while (nodesIt.hasNext()) { Node node = (Node) nodesIt.next(); String nodeStr = node.asXML(); String nodeName = node.getName(); if (TTXConstants.TUV.equalsIgnoreCase(node.getName())) { Attribute langAtt = ((Element) node).attribute(TTXConstants.TUV_ATT_LANG); String lang = null; if (langAtt != null) { lang = langAtt.getValue(); } if (sourceLanguage != null && sourceLanguage.equals(lang)) { // latestPosition = TTXConstants.IN_SOURCE_TUV; // Not handle source TUV for TTX off-line uploading. // domNodehandler(node, true); } else { // latestPosition = TTXConstants.IN_TARGET_TUV; domNodehandler(node, false); } } else { domNodehandler(node, false); } } } else { if (TTXConstants.UT.equalsIgnoreCase(elementName)) { Attribute displayTextAtt = element.attribute(TTXConstants.UT_ATT_DISPLAYTEXT); if (displayTextAtt != null) { String attValue = displayTextAtt.getValue(); if (attValue != null && attValue.startsWith(TTXConstants.TU_ID)) { // latestPosition = TTXConstants.TU_ID; String tuId = attValue.substring(attValue.indexOf(":") + 1).trim(); if (results != null && results.length() > 0) { results.append(TTXConstants.NEW_LINE).append(TTXConstants.NEW_LINE); } results.append(TTXConstants.HASH_MARK).append(tuId).append(TTXConstants.NEW_LINE); } else if (attValue != null && attValue.startsWith(TTXConstants.GS)) { Attribute typeValueAtt = element.attribute(TTXConstants.UT_ATT_TYPE); String typeValue = null; if (typeValueAtt != null) { typeValue = typeValueAtt.getValue(); } String gsTag = attValue.substring(attValue.indexOf(":") + 1).trim(); if (typeValue != null && TTXConstants.UT_ATT_TYPE_START.equalsIgnoreCase(typeValue)) { results.append("[").append(gsTag).append("]"); } else if (typeValue != null && TTXConstants.UT_ATT_TYPE_END.equalsIgnoreCase(typeValue)) { results.append("[/").append(gsTag).append("]"); } else { results.append("[").append(gsTag).append("]"); results.append("[/").append(gsTag).append("]"); } } } } else if (TTXConstants.DF.equalsIgnoreCase(elementName)) { // do not handle this. } } }
From source file:com.jeeframework.util.xml.XMLProperties.java
License:Open Source License
/** * Sets a property to an array of values. Multiple values matching the same property * is mapped to an XML file as multiple elements containing each value. * For example, using the name "foo.bar.prop", and the value string array containing * {"some value", "other value", "last value"} would produce the following XML: * <pre>/* www .j a va 2s . c om*/ * <foo> * <bar> * <prop>some value</prop> * <prop>other value</prop> * <prop>last value</prop> * </bar> * </foo> * </pre> * * @param name the name of the property. * @param values the values for the property (can be empty but not null). */ public void setProperties(String name, List<String> values, boolean isEncrypt) { String[] propName = parsePropertyName(name); // Search for this property by traversing down the XML hierarchy, // stopping one short. Element element = document.getRootElement(); for (int i = 0; i < propName.length - 1; i++) { // If we don't find this part of the property in the XML hierarchy // we add it as a new node if (element.element(propName[i]) == null) { element.addElement(propName[i]); } element = element.element(propName[i]); } String childName = propName[propName.length - 1]; // We found matching property, clear all children. List<Element> toRemove = new ArrayList<Element>(); Iterator<Element> iter = element.elementIterator(childName); while (iter.hasNext()) { toRemove.add(iter.next()); } for (iter = toRemove.iterator(); iter.hasNext();) { element.remove((Element) iter.next()); } // Add the new children. for (String value : values) { Element childElement = element.addElement(childName); if (value.startsWith("<![CDATA[")) { Iterator<Node> it = childElement.nodeIterator(); while (it.hasNext()) { Node node = it.next(); if (node instanceof CDATA) { childElement.remove(node); break; } } childElement.addCDATA(value.substring(9, value.length() - 3)); } else { String propValue = StringEscapeUtils.escapeXml(value); // check to see if the property is marked as encrypted if (isEncrypt) { propValue = EncryptUtil.desEncrypt(encryptKey, value); childElement.addAttribute(ENCRYPTED_ATTRIBUTE, "true"); } childElement.setText(propValue); } } saveProperties(); }
From source file:com.jeeframework.util.xml.XMLProperties.java
License:Open Source License
/** * Sets the value of the specified property. If the property doesn't * currently exist, it will be automatically created. * * @param name the name of the property to set. * @param value the new value for the property. * @param isEncrypt ?//from w w w. j a v a 2 s . c om */ public synchronized void setProperty(String name, String value, boolean isEncrypt) { if (!StringEscapeUtils.escapeXml(name).equals(name)) { throw new IllegalArgumentException("Property name cannot contain XML entities."); } if (name == null) { return; } if (value == null) { value = ""; } // Set cache correctly with prop name and value. propertyCache.put(name, value); String[] propName = parsePropertyName(name); // Search for this property by traversing down the XML hierarchy. Element element = document.getRootElement(); for (String aPropName : propName) { // If we don't find this part of the property in the XML hierarchy // we add it as a new node if (element.element(aPropName) == null) { element.addElement(aPropName); } element = element.element(aPropName); } // Set the value of the property in this node. if (value.startsWith("<![CDATA[")) { Iterator it = element.nodeIterator(); while (it.hasNext()) { Node node = (Node) it.next(); if (node instanceof CDATA) { element.remove(node); break; } } element.addCDATA(value.substring(9, value.length() - 3)); } else { String propValue = StringEscapeUtils.escapeXml(value); // check to see if the property is marked as encrypted if (isEncrypt) { propValue = EncryptUtil.desEncrypt(encryptKey, value); element.addAttribute(ENCRYPTED_ATTRIBUTE, "true"); } element.setText(propValue); } // Write the XML properties to disk saveProperties(); }
From source file:com.noterik.bart.fs.cloudexporter.DiskExporter.java
License:Open Source License
private static boolean exportNodes(String exporturl, String exportpath) { // if (exporturl.indexOf("/user")!=-1) return true; //Skip backing up the indexes /*// www. j a v a 2 s.c om if (exporturl.indexOf("/collectionindex")!=-1) return true; if (exporturl.indexOf("/keywordindex")!=-1) return true; if (exporturl.indexOf("/subtitlesindex")!=-1) return true; if (exporturl.indexOf("/speakersindex")!=-1) return true; if (exporturl.indexOf("/themesindex")!=-1) return true; if (exporturl.indexOf("/topicsearch")!=-1) return true; */ System.out.println("(" + (count++) + ") URL=" + exporturl); File dirs = new File(exportpath); boolean result = dirs.mkdirs(); if (dirs.exists()) { result = true; } if (!result) return false; Document exportXML = FSXMLRequestHandler.instance().handleDocGET(exporturl, "<properties><depth>0</depth></properties>"); if (exportXML != null) { for (Iterator i = exportXML.nodeIterator(); i.hasNext();) { Element fsnode = (Element) i.next(); if (fsnode.getName().equals("error")) return true; // Check if the current node is <error> for (Iterator j = fsnode.nodeIterator(); j.hasNext();) { Element mnode = (Element) j.next(); for (Iterator k = mnode.nodeIterator(); k.hasNext();) { Element dnode = (Element) k.next(); String name = dnode.getName(); String id = dnode.attributeValue("id"); //System.out.println("DNAME="+name); if (Arrays.asList(ignorelist).contains(name)) { System.out.println("ignoring " + name); } else if (!name.equals("properties")) { exportNodes(exporturl + "/" + name + "/" + id, exportpath + "/" + name + "/" + id); } else { try { MimeType mimetype = FSXMLRequestHandler.instance().getMimeTypeOfResource(exporturl); BufferedWriter propfile = new BufferedWriter( new FileWriter(exportpath + "/properties.txt")); String propbody = "<properties>\n"; // set the mimetype propbody += "\t<mimetype>"; if (mimetype.toString().equals("MIMETYPE_FS_SCRIPT")) { propbody += "application/fsscript"; } else if (mimetype.toString().equals("MIMETYPE_FS_COMMAND")) { propbody += "application/fscommand"; } else { propbody += "text/fsxml"; } propbody += "</mimetype>\n"; for (Iterator l = dnode.nodeIterator(); l.hasNext();) { Object p = l.next(); if (p instanceof Element) { Element pnode = (Element) p; String pname = pnode.getName(); String pvalue = pnode.getText(); propbody += "\t<" + pname + ">" + pvalue + "</" + pname + ">\n"; } else if (p instanceof DefaultText) { DefaultText tnode = (DefaultText) p; //System.out.println("DEFTEXT="+tnode.toString()); String pname = tnode.getName(); String pvalue = tnode.getText(); //propbody += "\t<"+pname+">"+pvalue+"</"+pname+">\n"; } else if (p instanceof DefaultComment) { DefaultComment cnode = (DefaultComment) p; String pname = cnode.getName(); String pvalue = cnode.getText(); //propbody += "\t<!-- <"+pname+">"+pvalue+"</"+pname+"> -->\n"; //System.out.println("DEFCOMMENT="+cnode.toString()); } else { System.out.println("UNCATCHED TYPE=" + p.toString()); } } propbody += "</properties>\n"; propfile.write(propbody); propfile.close(); } catch (Exception e) { System.out.println("PROP ERROR"); e.printStackTrace(); } } if (mnode.attributeValue("id") != null && mnode.attributeValue("referid") != null && !name.equals("user")) { try { System.out.println("MNODE2=" + mnode.asXML()); BufferedWriter attrfile = new BufferedWriter( new FileWriter(exportpath + "/attributes.txt")); String attrbody = "<attributes>\n"; attrbody += "\t<referid>" + mnode.attributeValue("referid") + "</referid>\n"; attrbody += "</attributes>\n"; attrfile.write(attrbody); attrfile.close(); } catch (Exception e) { e.printStackTrace(); } } } } } return true; } else { System.out.println("EXPORT URL NOT VALID (" + exporturl + ")"); return false; } }