List of usage examples for org.w3c.dom Node appendChild
public Node appendChild(Node newChild) throws DOMException;
newChild
to the end of the list of children of this node. From source file:com.laex.j2objc.AntDelegate.java
/** * Append exclude pattern to xml.//from w ww . j a va 2 s. co m * * @param path * the path * @param pats * the pats * @throws ParserConfigurationException * the parser configuration exception * @throws SAXException * the SAX exception * @throws IOException * Signals that an I/O exception has occurred. * @throws XPathExpressionException * the x path expression exception * @throws CoreException * the core exception * @throws TransformerException * the transformer exception */ private void appendExcludePatternToXML(IFile path, String[] pats) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException, CoreException, TransformerException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document dom = builder.parse(path.getContents()); XPathFactory xpathfactory = XPathFactory.newInstance(); XPath xpath = xpathfactory.newXPath(); XPathExpression expr = xpath.compile("project/target/move/fileset"); Node node = (Node) expr.evaluate(dom, XPathConstants.NODE); NodeList children = node.getChildNodes(); // don't why the last node in the xml should be indexed by length - 2 Node excludeCopy = children.item(children.getLength() - 2).cloneNode(true); for (String pattern : pats) { if (StringUtils.isNotEmpty(pattern.trim())) { Node newnode = excludeCopy.cloneNode(true); newnode.getAttributes().getNamedItem("name").setNodeValue(pattern); node.appendChild(newnode); } } // Setup transformers TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); StringWriter sw = new StringWriter(); transformer.transform(new DOMSource(dom), new StreamResult(sw)); String output = sw.getBuffer().toString(); // save the ouput ByteArrayInputStream bis = new ByteArrayInputStream(output.getBytes("utf-8")); path.setContents(bis, 0, null); }
From source file:org.openmrs.web.controller.report.CohortReportFormController.java
/** * @see org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse, java.lang.Object, * org.springframework.validation.BindException) *//* ww w . java 2s .c om*/ @Override protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object commandObj, BindException errors) throws Exception { CommandObject command = (CommandObject) commandObj; // do simpleframework serialization of everything but 'rows', and add those via handcoded xml, since // serializing them is not reversible ReportSchema rs = new ReportSchema(); rs.setReportSchemaId(command.getReportId()); rs.setName(command.getName()); rs.setDescription(command.getDescription()); rs.setReportParameters(command.getParameters()); rs.setDataSetDefinitions(new ArrayList<DataSetDefinition>()); Serializer serializer = OpenmrsUtil.getSerializer(); StringWriter sw = new StringWriter(); serializer.write(rs, sw); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setValidating(false); DocumentBuilder db = dbf.newDocumentBuilder(); Document xml = db.parse(new InputSource( new StringReader("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>" + sw.toString()))); Node node = findChild(xml, "reportSchema"); node = findChild(node, "dataSets"); Element dsd = xml.createElement("dataSetDefinition"); dsd.setAttribute("name", "cohorts"); dsd.setAttribute("class", "org.openmrs.report.CohortDataSetDefinition"); node.appendChild(dsd); Element strategies = xml.createElement("strategies"); strategies.setAttribute("class", "java.util.LinkedHashMap"); dsd.appendChild(strategies); Element descriptions = xml.createElement("descriptions"); descriptions.setAttribute("class", "java.util.LinkedHashMap"); dsd.appendChild(descriptions); for (CohortReportRow row : command.getRows()) { if (StringUtils.hasText(row.getQuery())) { Element entry = xml.createElement("entry"); strategies.appendChild(entry); Element nameEl = xml.createElement("string"); Text val = xml.createTextNode(row.getName()); val.setNodeValue(row.getName()); nameEl.appendChild(val); entry.appendChild(nameEl); Element cohort = xml.createElement("cohort"); entry.appendChild(cohort); cohort.setAttribute("class", "org.openmrs.reporting.PatientSearch"); Element strategyEl = xml.createElement("specification"); val = xml.createTextNode(row.getQuery()); val.setNodeValue(row.getQuery()); strategyEl.appendChild(val); cohort.appendChild(strategyEl); } if (StringUtils.hasText(row.getDescription())) { Element entry = xml.createElement("entry"); descriptions.appendChild(entry); Element el = xml.createElement("string"); Text val = xml.createTextNode(row.getName()); val.setNodeValue(row.getName()); el.appendChild(val); entry.appendChild(el); el = xml.createElement("string"); val = xml.createTextNode(row.getDescription()); val.setNodeValue(row.getDescription()); el.appendChild(val); entry.appendChild(el); } } // now turn this into an xml string System.setProperty("javax.xml.transform.TransformerFactory", "com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl"); TransformerFactory transfac = TransformerFactory.newInstance(); Transformer trans = transfac.newTransformer(); trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); trans.setOutputProperty(OutputKeys.INDENT, "yes"); trans.setOutputProperty(OutputKeys.METHOD, "xml"); StringWriter out = new StringWriter(); StreamResult result = new StreamResult(out); DOMSource source = new DOMSource(xml); trans.transform(source, result); String schemaXml = out.toString(); ReportSchemaXml rsx = new ReportSchemaXml(); rsx.populateFromReportSchema(rs); rsx.setXml(schemaXml); rsx.updateXmlFromAttributes(); rsx.setUuid(request.getParameter("parentUUID")); ReportService rptSvc = (ReportService) Context.getService(ReportService.class); if (rsx.getReportSchemaId() != null) { rptSvc.saveReportSchemaXml(rsx); } else { rptSvc.saveReportSchemaXml(rsx); } return new ModelAndView(new RedirectView(getSuccessView() + "?reportId=" + rsx.getReportSchemaId())); }
From source file:com.fiorano.openesb.application.aps.OutPortInst.java
/** * Returns the xml string equivalent of this object. * * @param document the input Document object * @return element node/* w ww . j a va 2 s. co m*/ * @exception FioranoException if an error occurs while creating the element * node. */ public Node toJXMLString(Document document) throws FioranoException { Node root0 = document.createElement("OutPortInst"); ((Element) root0).setAttribute("isSyncRequestType", "" + isSyncRequestType()); Node child = null; child = XMLDmiUtil.getNodeObject("Name", m_strPortName, document); if (child != null) { root0.appendChild(child); } if (!StringUtils.isEmpty(m_strDscription)) { child = XMLDmiUtil.getNodeObject("Description", m_strDscription, document); if (child != null) { root0.appendChild(child); } } boolean standardXSD = false; if ("ON_EXCEPTION".equals(m_strPortName)) standardXSD = CommonSchemas.ERROR_XSD == null ? m_strXSD == null : m_strXSD != null && CommonSchemas.ERROR_XSD.equals(m_strXSD); if (standardXSD) { Element elem = document.createElement("StandardXSD"); root0.appendChild(elem); } else if (m_strXSDRef != null) { child = XMLDmiUtil.getNodeObject(PortInstConstants.PORT_XSDREF, m_strXSDRef, document); root0.appendChild(child); } if (m_strContextXSL != null) { Element elem = document.createElement("SetContextXSL"); CDATASection cdata = document.createCDATASection(m_strContextXSL); elem.appendChild(cdata); root0.appendChild(elem); } if (m_strContextInfo != null) { Element elem = document.createElement("SetContextInfo"); CDATASection cdata = document.createCDATASection(m_strContextInfo); elem.appendChild(cdata); root0.appendChild(elem); } if (m_transformerType != null) { Element elem = document.createElement("SetTransformationType"); CDATASection cdata = document.createCDATASection(m_transformerType); elem.appendChild(cdata); root0.appendChild(elem); } if (!StringUtils.isEmpty(m_strJavaClass)) { child = XMLDmiUtil.getNodeObject("JavaClass", m_strJavaClass, document); if (child != null) { root0.appendChild(child); } } if (m_params != null && m_params.size() > 0) { Enumeration _enum = m_params.elements(); while (_enum.hasMoreElements()) { Param param = (Param) _enum.nextElement(); if (!StringUtils.isEmpty(param.getParamName()) && !StringUtils.isEmpty(param.getParamValue())) { if (!checkIfDefaultValue(param.getParamName(), param.getParamValue())) { Node paramNode = param.toJXMLString(document); root0.appendChild(paramNode); } } } } return root0; }
From source file:bridge.toolkit.commands.S1000DConverter.java
/** * The unit of processing work to be performed for the S1000DConverter module. * @see org.apache.commons.chain.Command#execute(org.apache.commons.chain.Context) *///ww w . j a v a2 s . c o m public boolean execute(Context ctx) { System.out.println("Executing S1000D Converter"); if ((ctx.get(Keys.SCPM_FILE) != null) && (ctx.get(Keys.RESOURCE_PACKAGE) != null)) { /* * check the output directory in the context if it does not exist make it */ if (!(ctx.containsKey(Keys.OUTPUT_DIRECTORY))) { ctx.put(Keys.OUTPUT_DIRECTORY, ""); } resourcepack = ctx.get(Keys.RESOURCE_PACKAGE).toString(); /* * if SCPM is 4.1 then Move the original file to the temp directory * in this file it will perform the downgrade to 4.0 version If * /scormContentPackage/content/scoEntry/scoEntryItem exists is a * 4.1 SCPM */ org.w3c.dom.Document new40 = null; File tempSCPM = null; try { new40 = getDoc(new File(ctx.get(Keys.SCPM_FILE).toString())); if (processXPathSingleNode("/scormContentPackage/content/scoEntry/scoEntryItem", new40) == null) { System.out.println("S1000D Converter Complete"); return CONTINUE_PROCESSING; } tempSCPM = File.createTempFile(new File(ctx.get(Keys.SCPM_FILE).toString()).getName(), ".xml"); copy(ctx.get(Keys.SCPM_FILE).toString(), tempSCPM.toString()); ctx.put(Keys.SCPM_FILE, tempSCPM.getAbsolutePath()); } catch (Exception e) { e.printStackTrace(); return PROCESSING_COMPLETE; } List<File> src_files = new ArrayList<File>(); try { src_files = getSourceFiles((String) ctx.get(Keys.RESOURCE_PACKAGE)); } catch (Exception npe) { System.out.println("The 'Resource Package' is empty."); return PROCESSING_COMPLETE; } /* * For each scoEntry adding sconEntryAddress and scoEntryStatus */ try { // getting the modelic and issuer from status SCPM modelic = processXPathSingleNode( "/scormContentPackage/identAndStatusSection/scormContentPackageAddress/scormContentPackageIdent/scormContentPackageCode/@modelIdentCode", new40).getNodeValue(); PackageIssuer = processXPathSingleNode( "/scormContentPackage/identAndStatusSection/scormContentPackageAddress/scormContentPackageIdent/scormContentPackageCode/@scormContentPackageIssuer", new40).getNodeValue(); PackageNumber = processXPathSingleNode( "/scormContentPackage/identAndStatusSection/scormContentPackageAddress/scormContentPackageIdent/scormContentPackageCode/@scormContentPackageNumber", new40).getNodeValue(); PackageVolume = processXPathSingleNode( "/scormContentPackage/identAndStatusSection/scormContentPackageAddress/scormContentPackageIdent/scormContentPackageCode/@scormContentPackageVolume", new40).getNodeValue(); securityClassification = processXPathSingleNode( "/scormContentPackage/identAndStatusSection/scormContentPackageStatus/security/@securityClassification", new40).getNodeValue(); ; qualityAssurance = processXPathSingleNode( "/scormContentPackage/identAndStatusSection/scormContentPackageStatus/qualityAssurance", new40); // getting the content node Node content = processXPathSingleNode("//content", new40); if (content != null) { // delete content.. Node contentclone = content.cloneNode(true); removeNode(content); // add the content Node.. org.w3c.dom.Element newcontent = new40.createElement("content"); // navigate through the tree seeking for scoEntry for (int i = 0; i < contentclone.getChildNodes().getLength(); i++) { Node node = contentclone.getChildNodes().item(i); if (node.getNodeName().equals("scoEntry")) { Node scoE = node.cloneNode(true); walkingthrough(scoE, new40); newcontent.appendChild(scoE); } } // add the content modified Node pm = processXPathSingleNode("//scormContentPackage", new40); pm.appendChild(newcontent); // re write on temp file the new XML.. writeOnDisk(tempSCPM, getXMLString(new40)); } } catch (Exception npe) { Writer writer = new StringWriter(); PrintWriter printWriter = new PrintWriter(writer); npe.printStackTrace(printWriter); writer.toString(); System.out.println("Error " + npe + " " + writer.toString()); return PROCESSING_COMPLETE; } System.out.println("Conversion of SCPM 4.1 to SCPM 4.0 was successful"); } else { System.out.println("One of the required Context entries for the " + this.getClass().getSimpleName() + " command to be executed was null"); return PROCESSING_COMPLETE; } return CONTINUE_PROCESSING; }
From source file:DOMProcessor.java
/** Adds a new element to the given one within the DOM. * @param name Name of the new element/*from ww w. java 2 s. c o m*/ * @param text Text to attach to element or null if none required. * @param existingElement Element onto which the new element should be attached. * @return New element in the DOM. */ public Node addElement(String name, String text, Node existingElement) { // Create the new element node and attach it to existing node. Node newNode = dom.createElement(name); existingElement.appendChild(newNode); // Add text if given. if (text != null) { Node textNode = dom.createTextNode(text); newNode.appendChild(textNode); } return newNode; }
From source file:com.adaptris.util.XmlUtils.java
/** * Method which modifies the value of the Node returned by the XPath query * specified, relative to the provided parent node. * * @param xp the XPath which will return the Node to be updated * @param v the new value to set the node to * @param root the root node to apply the XPath to * @throws Exception on error./*from w w w . j ava2 s.c om*/ */ public void setNodeValue(String xp, String v, Node root) throws Exception { Node n = xpath.selectSingleNode(root, xp); if (n == null) { n = createNode(xp); } try { setNodeValue(v, n); } catch (NullPointerException ne) { // Node has no children! Document d = n.getOwnerDocument(); Text t = d.createTextNode(v); n.appendChild(t); } }
From source file:ca.uqac.info.trace.generation.PQTraceGenerator.java
@Override public EventTrace generate() { EventTrace trace = new EventTrace(); // We choose the number of messages to produce int n_messages = super.nextInt(m_maxMessages - m_minMessages) + m_minMessages; for (int i = 0; i < n_messages; i++) { Node n = trace.getNode(); Vector<String> available_params = new Vector<String>(); // We produce the list of available parameters for this message available_params.add("p"); available_params.add("q"); // We choose the number of param-value pairs to generate int arity = super.nextInt(m_maxArity - m_minArity) + m_minArity; for (int j = 0; j < arity; j++) { // We generate as many param-value pairs as required int index = super.nextInt(available_params.size()); int value = super.nextInt(m_domainSize); if (m_minArity == 1 && m_maxArity == 1 && m_flatten) { // For traces of messages with fixed arity = 1, we // simply put the value as the text child of the "Event" // element n.appendChild(trace.createTextNode(new Integer(value).toString())); } else { Node el = trace.createElement(available_params.elementAt(index)); el.appendChild(trace.createTextNode(new Integer(value).toString())); n.appendChild(el);/* w ww . j a v a2 s . c o m*/ } } Event e = new Event(n); trace.add(e); } return trace; }
From source file:fi.csc.kapaVirtaAS.WSDLManipulator.java
public void generateVirtaKapaWSDL() throws Exception { // Fetch current WSDL-file File inputFile = new File("opiskelijatiedot.wsdl"); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(inputFile); doc.setXmlVersion("1.0"); doc.getDocumentElement().normalize(); // Manipulate WSDL to meet the requirements of xroad // Root element <wsdl:definitions> attribute manipulations Element root = doc.getDocumentElement(); root.setAttribute("xmlns:" + conf.getXroadSchemaPrefixForWSDL(), conf.getXroadSchema()); root.setAttribute("xmlns:" + conf.getXroadIdSchemaPrefixForWSDL(), conf.getXroadIdSchema()); root = replaceAttribute(root, "xmlns:tns", conf.getAdapterServiceSchema()); root = replaceAttribute(root, "targetNamespace", conf.getAdapterServiceSchema()); // Schema elements <xs:schema> attribute manipulations NodeList schemas = root.getElementsByTagName("xs:schema"); for (int i = 0; i < schemas.getLength(); ++i) { Node schema = schemas.item(i); if (schema != null) { NamedNodeMap schemaAttributes = schema.getAttributes(); if (schemaAttributes != null && schemaAttributes.getNamedItem("xmlns:virtaluku") != null) { schemaAttributes.getNamedItem("xmlns:virtaluku").setTextContent(conf.getAdapterServiceSchema()); if (schemaAttributes != null && schemaAttributes.getNamedItem("targetNamespace") != null) { schemaAttributes.getNamedItem("targetNamespace") .setTextContent(conf.getAdapterServiceSchema()); }//from ww w. j a v a 2s . com Element el = (Element) schema.appendChild(doc.createElement("xs:import")); el.setAttribute("id", conf.getXroadSchemaPrefixForWSDL()); el.setAttribute("namespace", conf.getXroadSchema()); el.setAttribute("schemaLocation", conf.getXroadSchema()); // Remove Request part from xs:element -elements NodeList elementsInSchema = schema.getChildNodes(); for (int j = 0; j < elementsInSchema.getLength(); ++j) { Element el1 = (Element) elementsInSchema.item(j); if (el1.getNodeName() == "xs:element") { replaceAttribute(el1, "name", StringUtils.substringBefore(el1.getAttribute("name"), "Request")); } } } } } // Append xroad request headers Element xroadReqHeadersElement = doc.createElement("wsdl:message"); xroadReqHeadersElement.setAttribute("name", "requestheader"); for (String xroadHeader : conf.getXroadHeaders()) { Element reqHeader = doc.createElement("wsdl:part"); reqHeader.setAttribute("name", xroadHeader); reqHeader.setAttribute("element", conf.getXroadSchemaPrefixForWSDL() + ":" + xroadHeader); xroadReqHeadersElement.appendChild(reqHeader); } root.appendChild(xroadReqHeadersElement); NodeList childrenList = root.getChildNodes(); for (int i = 0; i < childrenList.getLength(); ++i) { if (childrenList.item(i).getNodeName().contains(":binding")) { NodeList binding = childrenList.item(i).getChildNodes(); for (int j = 0; j < binding.getLength(); ++j) { if (binding.item(j).getNodeName().contains(":operation")) { Element el1 = (Element) binding.item(j) .appendChild(doc.createElement(conf.getXroadIdSchemaPrefixForWSDL() + ":version")); el1.setTextContent(conf.getVirtaVersionForXRoad()); for (Node child = binding.item(j).getFirstChild(); child != null; child = child .getNextSibling()) { // Append xroad wsdl:binding operation headers if (child.getNodeName().contains(":input") || child.getNodeName().contains(":output")) { Element el = (Element) child; for (String xroadHeader : conf.getXroadHeaders()) { el.appendChild(soapHeader(doc.createElement("soap:header"), "tns:requestheader", xroadHeader, "literal")); } } if (child.getNodeName().contains(":input")) { Element el = (Element) child; replaceAttribute(el, "name", StringUtils.substringBefore(el.getAttribute("name"), "Request")); } } } } // Remove Request from wsdl:message > wsdl:part element so that can see element } else if (childrenList.item(i).getNodeName().contains(":message") && childrenList.item(i) .getAttributes().getNamedItem("name").getNodeValue().contains("Request")) { Element part = (Element) childrenList.item(i).getFirstChild().getNextSibling(); replaceAttribute(part, "element", StringUtils.substringBefore(part.getAttribute("element"), "Request")); } // Change wsdl input names to meet XRoad standard if (childrenList.item(i).getNodeName().contains(":portType")) { NodeList binding = childrenList.item(i).getChildNodes(); for (int j = 0; j < binding.getLength(); ++j) { if (binding.item(j).getNodeName().contains(":operation")) { for (Node child = binding.item(j).getFirstChild(); child != null; child = child .getNextSibling()) { if (child.getNodeName().contains(":input")) { Element el = (Element) child; replaceAttribute(el, "name", StringUtils.substringBefore(el.getAttribute("name"), "Request")); } } } } } // Append kapaVirtaAS service address if (childrenList.item(i).getNodeName().contains(":service")) { NodeList service = childrenList.item(i).getChildNodes(); for (int j = 0; j < service.getLength(); ++j) { if (service.item(j).getNodeName().contains(":port")) { for (Node child = service.item(j).getFirstChild(); child != null; child = child .getNextSibling()) { if (child.getNodeName().contains(":address")) { Element el = (Element) child; replaceAttribute(el, "location", conf.getAdapterServiceSOAPURL()); } } } } } } // Write manipulated WSDL to file TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(new File(conf.getAdapterServiceWSDLPath() + "/kapavirta_as.wsdl")); transformer.transform(source, result); }
From source file:com.twinsoft.convertigo.engine.Context.java
public Node addTextNode(Node parentNode, String tagName, String text) { Document doc = parentNode.getOwnerDocument(); Element newElement = doc.createElement(tagName); if (text != null) { Text textElement = doc.createTextNode(text); newElement.appendChild(textElement); }//ww w . j a v a 2 s . c o m parentNode.appendChild(newElement); return newElement; }
From source file:XMLConfig.java
/** Set the value of the node or attribute specified by the DOM path. * @param path DOM path/* www . j ava2 s. c o m*/ * @param value node or attribute value * @param n node where the search should start * @param overwrite whether to overwrite (true) or add (false) -- only applies for last node! * @return the node that was created, or the parent node of the attribute if it was an attribute */ public Node set(String path, String value, Node n, boolean overwrite) { if (isDelegated()) { return _parent.set(path, value, n, overwrite); } int dotPos = path.lastIndexOf('.'); Node node; if (dotPos == 0) { node = n; } else { node = createNode(path, n, overwrite); } if (dotPos >= 0) { Element e = (Element) node; e.setAttribute(path.substring(dotPos + 1), value); } else { node.appendChild(_document.createTextNode(value)); } return node; }