List of usage examples for org.w3c.dom Document createElement
public Element createElement(String tagName) throws DOMException;
From source file:Main.java
/** * Method to delete old elements and add new elements in target file based on tag name of source file. * * @param source//from w w w . java2 s. c om * @param target * @param sourceTagName * @param targetTagNameParent * @param targetTagNameChild * @return document * @throws ParseException */ public static Document addNewElements(Document source, Document target, String sourceTagName, String targetTagNameParent, String targetTagNameChild, List<String> ignoreList) throws ParseException { //list for attributes to be more dynamic if reuse //remove old entries target = removeAllOptions(target); // add new entries NodeList nameList = source.getElementsByTagName(sourceTagName); NodeList parents = target.getElementsByTagName(targetTagNameParent); Element parent = (Element) parents.item(0); // g:options - only 1 // element //add space placeholder as first entry Element o = target.createElement(targetTagNameChild); o.setAttribute("g:value", ""); o.setAttribute("g:label", ""); parent.appendChild(o); for (int i = 0; i < nameList.getLength(); i++) { String value = nameList.item(i).getTextContent(); if (value != null && !value.equals("") && !ignoreList.contains(value)) { Element p = target.createElement(targetTagNameChild); p.setAttribute("g:value", value); p.setAttribute("g:label", value); parent.appendChild(p); } } return changeDate(target); }
From source file:net.sourceforge.eclipsetrader.charts.ChartsPlugin.java
public static void saveDefaultChart(Chart chart) { Log logger = LogFactory.getLog(ChartsPlugin.class); SimpleDateFormat dateTimeFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss"); //$NON-NLS-1$ try {//from w ww.j av a2 s .co m DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document document = builder.getDOMImplementation().createDocument(null, "chart", null); //$NON-NLS-1$ Element root = document.getDocumentElement(); Element node = document.createElement("title"); //$NON-NLS-1$ node.appendChild(document.createTextNode(chart.getTitle())); root.appendChild(node); node = document.createElement("compression"); //$NON-NLS-1$ node.appendChild(document.createTextNode(String.valueOf(chart.getCompression()))); root.appendChild(node); node = document.createElement("period"); //$NON-NLS-1$ node.appendChild(document.createTextNode(String.valueOf(chart.getPeriod()))); root.appendChild(node); node = document.createElement("autoScale"); //$NON-NLS-1$ node.appendChild(document.createTextNode(String.valueOf(chart.isAutoScale()))); root.appendChild(node); if (chart.getBeginDate() != null) { node = document.createElement("begin"); //$NON-NLS-1$ node.appendChild(document.createTextNode(dateTimeFormat.format(chart.getBeginDate()))); root.appendChild(node); } if (chart.getEndDate() != null) { node = document.createElement("end"); //$NON-NLS-1$ node.appendChild(document.createTextNode(dateTimeFormat.format(chart.getEndDate()))); root.appendChild(node); } for (int r = 0; r < chart.getRows().size(); r++) { ChartRow row = (ChartRow) chart.getRows().get(r); row.setId(new Integer(r)); Element rowNode = document.createElement("row"); //$NON-NLS-1$ root.appendChild(rowNode); for (int t = 0; t < row.getTabs().size(); t++) { ChartTab tab = (ChartTab) row.getTabs().get(t); tab.setId(new Integer(t)); Element tabNode = document.createElement("tab"); //$NON-NLS-1$ tabNode.setAttribute("label", tab.getLabel()); //$NON-NLS-1$ rowNode.appendChild(tabNode); for (int i = 0; i < tab.getIndicators().size(); i++) { ChartIndicator indicator = (ChartIndicator) tab.getIndicators().get(i); indicator.setId(new Integer(i)); Element indicatorNode = document.createElement("indicator"); //$NON-NLS-1$ indicatorNode.setAttribute("pluginId", indicator.getPluginId()); //$NON-NLS-1$ tabNode.appendChild(indicatorNode); for (Iterator iter = indicator.getParameters().keySet().iterator(); iter.hasNext();) { String key = (String) iter.next(); node = document.createElement("param"); //$NON-NLS-1$ node.setAttribute("key", key); //$NON-NLS-1$ node.setAttribute("value", (String) indicator.getParameters().get(key)); //$NON-NLS-1$ indicatorNode.appendChild(node); } } for (int i = 0; i < tab.getObjects().size(); i++) { ChartObject object = (ChartObject) tab.getObjects().get(i); object.setId(new Integer(i)); Element indicatorNode = document.createElement("object"); //$NON-NLS-1$ indicatorNode.setAttribute("pluginId", object.getPluginId()); //$NON-NLS-1$ tabNode.appendChild(indicatorNode); for (Iterator iter = object.getParameters().keySet().iterator(); iter.hasNext();) { String key = (String) iter.next(); node = document.createElement("param"); //$NON-NLS-1$ node.setAttribute("key", key); //$NON-NLS-1$ node.setAttribute("value", (String) object.getParameters().get(key)); //$NON-NLS-1$ indicatorNode.appendChild(node); } } } } TransformerFactory factory = TransformerFactory.newInstance(); try { factory.setAttribute("indent-number", new Integer(4)); //$NON-NLS-1$ } catch (Exception e) { } Transformer transformer = factory.newTransformer(); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$ transformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1"); //$NON-NLS-1$ transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$ transformer.setOutputProperty("{http\u003a//xml.apache.org/xslt}indent-amount", "4"); //$NON-NLS-1$ //$NON-NLS-2$ DOMSource source = new DOMSource(document); File file = ChartsPlugin.getDefault().getStateLocation().append("defaultChart.xml").toFile(); //$NON-NLS-1$ BufferedWriter out = new BufferedWriter(new FileWriter(file)); StreamResult result = new StreamResult(out); transformer.transform(source, result); out.flush(); out.close(); } catch (Exception e) { logger.error(e.toString(), e); } }
From source file:com.ephesoft.dcma.util.XMLUtil.java
/** * To append Leaf Child./*from w w w . j a va 2 s .c om*/ * * @param doc Document * @param parent Node * @param childName String * @param childData String */ public static void appendLeafChild(Document doc, Node parent, String childName, String childData) { Element child = doc.createElement(childName); if (childData != null && childData.length() != 0) { Text text = doc.createTextNode(childData); child.appendChild(text); } parent.appendChild(child); }
From source file:Main.java
private static Element getChildElement(Document document, Element origElement, String subElementName) { NodeList buildNodes = origElement.getChildNodes(); int numChildrenOfOrig = buildNodes.getLength(); for (int indexChildOfOrig = 0; indexChildOfOrig < numChildrenOfOrig; indexChildOfOrig++) { Node child = buildNodes.item(indexChildOfOrig); if (child.getNodeName().equals(subElementName)) { return (Element) child; }/* ww w.j ava 2 s. com*/ } //if we are here, the child node was never found, so create it now Element newElem = document.createElement(subElementName); origElement.appendChild(newElem); return newElem; }
From source file:Main.java
/** * Converts a map to XML, where parent is the parent element, and every * other element is of the form <key>value</key> or <listElementName>listvalue</listElementName> * for each list index. The list elements MUST be Strings if they are to * have text nodes. But, they may also be another Map with key/value * pairs./*w w w.j a v a2s. c o m*/ * <p/> * We assume that every key is an actual XML compatible element name; i.e. a * String object. The values will be XML encoded automatically. * * @param elements the elements, whether a list of elements or a map * of key/value pairs * @param parentElement the parent element to append the new child to * @param document the XML document to create new elements in * @param listElementName the name for the element, for every element in the * List * * @throws ParserConfigurationException if a configuration error occurs */ public static void mapToNode(final Object elements, final Element parentElement, final Document document, final String listElementName) throws ParserConfigurationException { Object value; if (elements instanceof Map) { final Map map = (Map) elements; final Iterator it = map.keySet().iterator(); Element tmp; while (it.hasNext()) { final String key = (String) it.next(); value = map.get(key); if (value instanceof Map) { tmp = document.createElement(key); mapToNode(value, tmp, document, null); parentElement.appendChild(tmp); } else if (value instanceof List) { mapToNode(value, parentElement, document, key); } else { tmp = document.createElement(key); if (value != null) { // null elements don't get in tmp.appendChild(document.createTextNode((String) value)); parentElement.appendChild(tmp); } } } } else if (elements instanceof List) { if (listElementName == null || "".equals(listElementName.trim())) { throw new IllegalArgumentException( "listElementName can never be null if a list is passed " + "in for elements"); } final List list = (List) elements; for (int index = 0; index < list.size(); index++) { final Object element = list.get(index); if (element instanceof String) { // text node final String text = (String) list.get(index); final Element tmp = document.createElement(listElementName); tmp.appendChild(document.createTextNode(text)); parentElement.appendChild(tmp); } else if (element instanceof Map) { // sub elements that have key/value pairs, or key/List pairs final Element tmp = document.createElement(listElementName); parentElement.appendChild(tmp); mapToNode(element, tmp, document, null); } else if (element instanceof List) { throw new IllegalArgumentException( "List not supported " + "inside of List, cannot determine element name"); } } } else { throw new IllegalArgumentException("unsupported class type for " + "mapToXML"); } }
From source file:com.microfocus.application.automation.tools.octane.executor.TestExecutionJobCreatorService.java
private static String prepareMtbxData(List<TestExecutionInfo> tests) throws IOException { /*<Mtbx>//from w w w . j ava 2s. c om <Test name="test1" path="${WORKSPACE}\${CHECKOUT_SUBDIR}\APITest1"> <Parameter name="A" value="abc" type="string"/> <DataTable path="${WORKSPACE}\aa\bbb.xslx"/> . </Test> <Test name="test2" path="${WORKSPACE}\${CHECKOUT_SUBDIR}\test2"> <Parameter name="p1" value="123" type="int"/> <Parameter name="p4" value="123.4" type="float"/> . </Test> </Mtbx>*/ try { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.newDocument(); Element rootElement = doc.createElement("Mtbx"); doc.appendChild(rootElement); for (TestExecutionInfo test : tests) { Element testElement = doc.createElement("Test"); String packageAndTestName = (StringUtils.isNotEmpty(test.getPackageName()) ? test.getPackageName() + "\\" : "") + test.getTestName(); testElement.setAttribute("name", packageAndTestName); String path = "${WORKSPACE}\\${CHECKOUT_SUBDIR}" + (StringUtils.isEmpty(test.getPackageName()) ? "" : SdkConstants.FileSystem.WINDOWS_PATH_SPLITTER + test.getPackageName()) + SdkConstants.FileSystem.WINDOWS_PATH_SPLITTER + test.getTestName(); testElement.setAttribute("path", path); if (StringUtils.isNotEmpty(test.getDataTable())) { Element dataTableElement = doc.createElement("DataTable"); dataTableElement.setAttribute("path", "${WORKSPACE}\\${CHECKOUT_SUBDIR}" + SdkConstants.FileSystem.WINDOWS_PATH_SPLITTER + test.getDataTable()); testElement.appendChild(dataTableElement); } rootElement.appendChild(testElement); } TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); StringWriter writer = new StringWriter(); transformer.transform(new DOMSource(doc), new StreamResult(writer)); return writer.toString(); } catch (Exception e) { throw new IOException("Failed to build MTBX content : " + e.getMessage()); } }
From source file:com.meltmedia.cadmium.core.util.WarUtils.java
/** * Adds a shiro environment listener to load the shiro config file. * @param doc The xml DOM document to create the new xml elements with. * @param root The xml Element node to add the listener to. *///from w w w. j ava2s.c o m public static void addListener(Document doc, Element root) { Element listener = doc.createElement("listener"); Element listenerClass = doc.createElement("listener-class"); listener.appendChild(listenerClass); listenerClass.appendChild(doc.createTextNode("org.apache.shiro.web.env.EnvironmentLoaderListener")); addRelativeTo(root, listener, "listener", true); }
From source file:com.photon.phresco.framework.commons.QualityUtil.java
private static Node appendHeaderManager(Document document, Map<String, String> headersMap) { Node headerManager = document.createElement("HeaderManager"); NamedNodeMap attributes = headerManager.getAttributes(); attributes.setNamedItem(createAttribute(document, "guiclass", "HeaderPanel")); attributes.setNamedItem(createAttribute(document, "testclass", "HeaderManager")); attributes.setNamedItem(createAttribute(document, "testname", "HTTP Header Manager")); attributes.setNamedItem(createAttribute(document, "enabled", "true")); appendHeaderManagerCollectionProp(document, headerManager, headersMap); return headerManager; }
From source file:com.meltmedia.cadmium.core.util.WarUtils.java
/** * Adds the shiro filter to a web.xml file. * @param doc The xml DOM document to create the new xml elements with. * @param root The xml Element node to add the filter to. *//* w w w . ja va2 s.co m*/ public static void addFilter(Document doc, Element root) { Element filter = doc.createElement("filter"); Element filterName = doc.createElement("filter-name"); filterName.appendChild(doc.createTextNode("ShiroFilter")); filter.appendChild(filterName); Element filterClass = doc.createElement("filter-class"); filterClass.appendChild(doc.createTextNode("org.apache.shiro.web.servlet.ShiroFilter")); filter.appendChild(filterClass); addRelativeTo(root, filter, "filter", true); }
From source file:Main.java
@SuppressWarnings("null") public static void copyInto(Node src, Node dest) throws DOMException { Document factory = dest.getOwnerDocument(); //Node start = src; Node parent = null;// www .j a v a2 s. c o m Node place = src; // traverse source tree while (place != null) { // copy this node Node node = null; int type = place.getNodeType(); switch (type) { case Node.CDATA_SECTION_NODE: { node = factory.createCDATASection(place.getNodeValue()); break; } case Node.COMMENT_NODE: { node = factory.createComment(place.getNodeValue()); break; } case Node.ELEMENT_NODE: { Element element = factory.createElement(place.getNodeName()); node = element; NamedNodeMap attrs = place.getAttributes(); int attrCount = attrs.getLength(); for (int i = 0; i < attrCount; i++) { Attr attr = (Attr) attrs.item(i); String attrName = attr.getNodeName(); String attrValue = attr.getNodeValue(); element.setAttribute(attrName, attrValue); /* if (domimpl && !attr.getSpecified()) { ((Attr) element.getAttributeNode(attrName)).setSpecified(false); } */ } break; } case Node.ENTITY_REFERENCE_NODE: { node = factory.createEntityReference(place.getNodeName()); break; } case Node.PROCESSING_INSTRUCTION_NODE: { node = factory.createProcessingInstruction(place.getNodeName(), place.getNodeValue()); break; } case Node.TEXT_NODE: { node = factory.createTextNode(place.getNodeValue()); break; } default: { throw new IllegalArgumentException( "can't copy node type, " + type + " (" + node.getNodeName() + ')'); } } dest.appendChild(node); // iterate over children if (place.hasChildNodes()) { parent = place; place = place.getFirstChild(); dest = node; } else if (parent == null) { place = null; } else { // advance place = place.getNextSibling(); while (place == null && parent != null && dest != null) { place = parent.getNextSibling(); parent = parent.getParentNode(); dest = dest.getParentNode(); } } } }