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:org.docx4j.XmlUtils.java
/** * Copy a node from one DOM document to another. Used * to avoid relying on an underlying implementation which might * not support importNode //from ww w. ja va2 s . c om * (eg Xalan's org.apache.xml.dtm.ref.DTMNodeProxy). * * WARNING: doesn't fully support namespaces! * * @param sourceNode * @param destParent */ public static void treeCopy(Node sourceNode, Node destParent) { // http://osdir.com/ml/text.xml.xerces-j.devel/2004-04/msg00066.html // suggests the problem has been fixed? // source node maybe org.apache.xml.dtm.ref.DTMNodeProxy // (if its xslt output we are copying) // or com.sun.org.apache.xerces.internal.dom.CoreDocumentImpl // (if its marshalled JAXB) log.debug("node type" + sourceNode.getNodeType()); switch (sourceNode.getNodeType()) { case Node.DOCUMENT_NODE: // type 9 case Node.DOCUMENT_FRAGMENT_NODE: // type 11 // log.debug("DOCUMENT:" + w3CDomNodeToString(sourceNode) ); // if (sourceNode.getChildNodes().getLength()==0) { // log.debug("..no children!"); // } // recurse on each child NodeList nodes = sourceNode.getChildNodes(); if (nodes != null) { for (int i = 0; i < nodes.getLength(); i++) { log.debug("child " + i + "of DOCUMENT_NODE"); //treeCopy((DTMNodeProxy)nodes.item(i), destParent); treeCopy((Node) nodes.item(i), destParent); } } break; case Node.ELEMENT_NODE: // Copy of the node itself log.debug("copying: " + sourceNode.getNodeName()); Node newChild; if (destParent instanceof Document) { newChild = ((Document) destParent).createElementNS(sourceNode.getNamespaceURI(), sourceNode.getLocalName()); } else if (sourceNode.getNamespaceURI() != null) { newChild = destParent.getOwnerDocument().createElementNS(sourceNode.getNamespaceURI(), sourceNode.getLocalName()); } else { newChild = destParent.getOwnerDocument().createElement(sourceNode.getNodeName()); } destParent.appendChild(newChild); // .. its attributes NamedNodeMap atts = sourceNode.getAttributes(); for (int i = 0; i < atts.getLength(); i++) { Attr attr = (Attr) atts.item(i); // log.debug("attr.getNodeName(): " + attr.getNodeName()); // log.debug("attr.getNamespaceURI(): " + attr.getNamespaceURI()); // log.debug("attr.getLocalName(): " + attr.getLocalName()); // log.debug("attr.getPrefix(): " + attr.getPrefix()); if (attr.getNodeName().startsWith("xmlns:")) { /* A document created from a dom4j document using dom4j 1.6.1's io.domWriter does this ?! attr.getNodeName(): xmlns:w attr.getNamespaceURI(): null attr.getLocalName(): null attr.getPrefix(): null unless i'm doing something wrong, this is another reason to remove use of dom4j from docx4j */ ; // this is a namespace declaration. not our problem } else if (attr.getNamespaceURI() == null) { //log.debug("attr.getLocalName(): " + attr.getLocalName() + "=" + attr.getValue()); ((org.w3c.dom.Element) newChild).setAttribute(attr.getName(), attr.getValue()); } else if (attr.getNamespaceURI().equals("http://www.w3.org/2000/xmlns/")) { ; // this is a namespace declaration. not our problem } else if (attr.getNodeName() != null) { // && attr.getNodeName().equals("xml:space")) { // restrict this fix to xml:space only, if necessary // Necessary when invoked from BindingTraverserXSLT, // com.sun.org.apache.xerces.internal.dom.AttrNSImpl // otherwise it was becoming w:space="preserve"! /* eg xml:space * attr.getNodeName(): xml:space attr.getNamespaceURI(): http://www.w3.org/XML/1998/namespace attr.getLocalName(): space attr.getPrefix(): xml */ ((org.w3c.dom.Element) newChild).setAttributeNS(attr.getNamespaceURI(), attr.getNodeName(), attr.getValue()); } else { ((org.w3c.dom.Element) newChild).setAttributeNS(attr.getNamespaceURI(), attr.getLocalName(), attr.getValue()); } } // recurse on each child NodeList children = sourceNode.getChildNodes(); if (children != null) { for (int i = 0; i < children.getLength(); i++) { //treeCopy( (DTMNodeProxy)children.item(i), newChild); treeCopy((Node) children.item(i), newChild); } } break; case Node.TEXT_NODE: // Where destParent is com.sun.org.apache.xerces.internal.dom.DocumentImpl, // destParent.getOwnerDocument() returns null. // #document ; com.sun.org.apache.xerces.internal.dom.DocumentImpl // System.out.println(sourceNode.getNodeValue()); //System.out.println(destParent.getNodeName() + " ; " + destParent.getClass().getName() ); if (destParent.getOwnerDocument() == null && destParent.getNodeName().equals("#document")) { Node textNode = ((Document) destParent).createTextNode(sourceNode.getNodeValue()); destParent.appendChild(textNode); } else { Node textNode = destParent.getOwnerDocument().createTextNode(sourceNode.getNodeValue()); // Warning: If you attempt to write a single "&" character, it will be converted to & // even if it doesn't look like that with getNodeValue() or getTextContent()! // So avoid any tricks with entities! See notes in docx2xhtmlNG2.xslt Node appended = destParent.appendChild(textNode); } break; // case Node.CDATA_SECTION_NODE: // writer.write("<![CDATA[" + // node.getNodeValue() + "]]>"); // break; // // case Node.COMMENT_NODE: // writer.write(indentLevel + "<!-- " + // node.getNodeValue() + " -->"); // writer.write(lineSeparator); // break; // // case Node.PROCESSING_INSTRUCTION_NODE: // writer.write("<?" + node.getNodeName() + // " " + node.getNodeValue() + // "?>"); // writer.write(lineSeparator); // break; // // case Node.ENTITY_REFERENCE_NODE: // writer.write("&" + node.getNodeName() + ";"); // break; // // case Node.DOCUMENT_TYPE_NODE: // DocumentType docType = (DocumentType)node; // writer.write("<!DOCTYPE " + docType.getName()); // if (docType.getPublicId() != null) { // System.out.print(" PUBLIC \"" + // docType.getPublicId() + "\" "); // } else { // writer.write(" SYSTEM "); // } // writer.write("\"" + docType.getSystemId() + "\">"); // writer.write(lineSeparator); // break; } }
From source file:org.easyrec.service.core.impl.ProfileServiceImpl.java
/** * Inserts a new element and value into an XML Document at the position given in xPathExpression * relative to the Node given in startNode. * * @param doc the Document in which the Element is inserted * @param startNode the Node in the Document used as start point for the XPath Expression * @param xPathExpression the XPath from the startNode to the new Element * @param value the value of the new Element *//*from w w w . j a v a 2 s. c om*/ private Node insertElement(Document doc, Node startNode, String xPathExpression, String value) { if (!"".equals(xPathExpression)) { String[] xPathTokens = xPathExpression.split("/"); for (String tag : xPathTokens) { if (!"".equals(tag)) { Element el = doc.createElement(tag); startNode.appendChild(el); startNode = startNode.getLastChild(); } } if (value != null) startNode.setTextContent(value); } return startNode; }
From source file:org.easyrec.service.domain.profile.impl.ProfileServiceImpl.java
public void insertOrUpdateMultiDimension(Integer tenantId, Integer itemId, String itemTypeId, String dimensionXPath, List<String> values) { XPathFactory xpf = XPathFactory.newInstance(); try {//from ww w . jav a2s .c o m // load and parse the profile DocumentBuilder db = validationParsers.get(tenantId).get(itemTypeId); Document doc = db.parse(new InputSource(new StringReader(getProfile(tenantId, itemId, itemTypeId)))); // check if the element exists Node node = null; Node parent = null; XPath xp = xpf.newXPath(); for (Iterator<String> it = values.iterator(); it.hasNext();) { String value = it.next(); // look if value already exists node = (Node) xp.evaluate(dimensionXPath + "[text()='" + value + "']", doc, XPathConstants.NODE); // if value exists, value can be discarded if (node != null) { // optimization: if a node was found, store the parent; later no new XPath evaluation is necessary parent = node.getParentNode(); it.remove(); } } if (values.isEmpty()) return; // nothing left to do String parentPath = dimensionXPath.substring(0, dimensionXPath.lastIndexOf("/")); // find path to parent if (parent == null) { String tmpPath = parentPath; while (parent == null) { tmpPath = parentPath.substring(0, tmpPath.lastIndexOf("/")); parent = (Node) xp.evaluate(tmpPath, doc, XPathConstants.NODE); } parent = insertElement(doc, parent, parentPath.substring(tmpPath.length()), null); } String tag = dimensionXPath.substring(parentPath.length() + 1); for (String value : values) { Element el = doc.createElement(tag); el.setTextContent(value); parent.appendChild(el); } StringWriter writer = new StringWriter(); Result result = new StreamResult(writer); trans.transform(new DOMSource(doc), result); writer.close(); String xml = writer.toString(); logger.debug(xml); storeProfile(tenantId, itemId, itemTypeId, xml, true); } catch (Exception e) { logger.error("Error inserting Multi Dimension: " + e.getMessage()); e.printStackTrace(); } }
From source file:org.ebayopensource.turmeric.eclipse.resources.util.SOAIntfUtil.java
/** * The format should be the following/*w w w .ja v a 2s. c o m*/ * <wsdl:service name="CreativeService"> * <wsdl:documentation> * <version>1.0</version> * </wsdl:documentation> * ... * * @param project the project * @param newVersion the new version * @param monitor the monitor * @throws Exception the exception */ public static void modifyWsdlAppInfoVersion(final IProject project, final String newVersion, IProgressMonitor monitor) throws Exception { monitor.setTaskName("Modifying service WSDL..."); final String serviceName = project.getName(); final IFile wsdlFile = SOAServiceUtil.getWsdlFile(project, serviceName); InputStream ins = null; Definition wsdl = null; try { ins = wsdlFile.getContents(); wsdl = WSDLUtil.readWSDL(ins); } finally { IOUtils.closeQuietly(ins); } monitor.worked(10); if (wsdl == null) return; DOMParser domParser = new DOMParser(); Document doc = null; try { ins = wsdlFile.getContents(); domParser.parse(new InputSource(ins)); doc = domParser.getDocument(); } finally { IOUtils.closeQuietly(ins); } monitor.worked(10); if (doc == null) return; Node wsdlNode = doc.getFirstChild(); Node serviceNode = null; for (int i = wsdlNode.getChildNodes().getLength() - 1; i >= 0; i--) { Node node = wsdlNode.getChildNodes().item(i); if (node.getNodeType() == Node.ELEMENT_NODE && ELEM_NAME_SERVICE.equals(node.getLocalName())) { serviceNode = node; break; } } monitor.worked(10); if (serviceNode == null) return; Node documentationNode = null; for (int i = 0; i < serviceNode.getChildNodes().getLength(); i++) { Node node = serviceNode.getChildNodes().item(i); if (ELEM_NAME_DOCUMENTATION.equals(node.getLocalName())) { documentationNode = node; } } monitor.worked(10); boolean needUpdateWsdl = false; if (documentationNode != null) { //we found the documentation node Node verNode = null; for (int i = 0; i < documentationNode.getChildNodes().getLength(); i++) { Node node = documentationNode.getChildNodes().item(i); if (ELEM_NAME_VERSION_V2_CAMEL_CASE.equals(node.getLocalName()) || ELEM_NAME_VERSION_V3_CAMEL_CASE.equals(node.getLocalName())) { verNode = node; break; } } if (verNode == null) { // add version node to document node if there is no version // node. Element v3Version = doc.createElement("version"); Text versionText = doc.createTextNode(newVersion); v3Version.appendChild(versionText); documentationNode.appendChild(v3Version); needUpdateWsdl = true; } else { if (ELEM_NAME_VERSION_V2_CAMEL_CASE.equals(verNode.getLocalName())) { // if current version node is V2 format, replace it with V3 // format Element v3Version = doc.createElement("version"); Text versionText = doc.createTextNode(newVersion); v3Version.appendChild(versionText); documentationNode.replaceChild(v3Version, verNode); needUpdateWsdl = true; } else { // current version format is V3, update version value. for (int i = 0; i < verNode.getChildNodes().getLength(); i++) { Node node = verNode.getChildNodes().item(i); if (node.getNodeType() == Node.TEXT_NODE && newVersion.equals(node.getNodeValue()) == false) { logger.warning("Version defined in WSDL's service section->", node.getNodeValue(), " is older than the new version->", newVersion); node.setNodeValue(newVersion); needUpdateWsdl = true; break; } } } } } monitor.worked(10); if (needUpdateWsdl == true) { FileWriter writer = null; try { writer = new FileWriter(wsdlFile.getLocation().toFile()); XMLUtil.writeXML(wsdlNode, writer); } finally { IOUtils.closeQuietly(writer); wsdlFile.refreshLocal(IResource.DEPTH_ONE, monitor); } } else { logger.info("WSDL already have the correct version '", newVersion, "', skip the modification for WSDL->", wsdlFile.getLocation()); } monitor.worked(10); }
From source file:org.eclipse.lyo.testsuite.oslcv2.asset.UsageCaseXmlTests.java
@Test public void publishUsageCase() throws IOException, ParseException, ParserConfigurationException, SAXException, TransformerException, XPathException { // Get url//from ww w . ja va2s . co m ArrayList<String> serviceUrls = getServiceProviderURLsUsingXML(setupProps.getProperty("baseUri")); ArrayList<String> capabilityURLsUsingRdfXml = TestsBase.getCapabilityURLsUsingRdfXml( OSLCConstants.CREATION_PROP, serviceUrls, useDefaultUsageForCreation, null); currentUrl = capabilityURLsUsingRdfXml.get(0); // Create the asset assetUrl = createAsset(xmlCreateTemplate); assertTrue("The location of the asset after it was create was not returned", assetUrl != null); // Add the artifact to the asset String artifactFactory = getArtifactFactory(); Header[] header = addHeader(new BasicHeader("oslc_asset.name", "/helpFolder/help")); //String fileName = setupProps.getProperty("createTemplateArtifactXmlFile"); String fileName = setupProps.getProperty("createTemplateXmlFile"); assertTrue("There needs to be an artifact template file", fileName != null); String artifact = OSLCUtils.readFileByNameAsString(fileName); HttpResponse response = OSLCUtils.postDataToUrl(artifactFactory, creds, OSLCConstants.CT_XML, OSLCConstants.CT_XML, artifact, header); EntityUtils.consume(response.getEntity()); assertTrue("Expected " + HttpStatus.SC_OK + ", received " + response.getStatusLine().getStatusCode(), response.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED); // Get updated asset and update the artifact HttpResponse resp = getAssetResponse(); String content = EntityUtils.toString(resp.getEntity()); Document document = OSLCUtils.createXMLDocFromResponseBody(content); EntityUtils.consume(resp.getEntity()); String path = "/rdf:RDF/oslc_asset:Asset/oslc_asset:artifact[1]/oslc_asset:Artifact"; XPath xpath = OSLCUtils.getXPath(); Node artifactNode = (Node) xpath.evaluate(path, document, XPathConstants.NODE); NodeList artifactKids = artifactNode.getChildNodes(); Node label = null; for (int i = 0; i < artifactKids.getLength(); i++) { if (artifactKids.item(i).getNodeName().equals("oslc:label")) { label = artifactKids.item(i); break; } } String labelValue = "this value was changed"; if (label == null) { label = document.createElement("oslc:label"); label.setTextContent(labelValue); artifactNode.appendChild(label); } else { label.setTextContent(labelValue); } // Update asset content = OSLCUtils.createStringFromXMLDoc(document); putAsset(content); // Check to see if the label was updated resp = getAssetResponse(); content = EntityUtils.toString(resp.getEntity()); document = OSLCUtils.createXMLDocFromResponseBody(content); EntityUtils.consume(resp.getEntity()); path = "/rdf:RDF/oslc_asset:Asset/oslc_asset:artifact[1]/oslc_asset:Artifact/oslc:label"; xpath = OSLCUtils.getXPath(); label = (Node) xpath.evaluate(path, document, XPathConstants.NODE); assertTrue("Could not find the artifact's label node", label != null); assertEquals("The label was not updated properly", labelValue, label.getTextContent()); }
From source file:org.eclipse.skalli.core.extension.DataMigration11.java
private void addPeopleSection(Document doc, Node parentNode, String name, List<String> people) { Element peopleElement = doc.createElement(name); addPeople(doc, peopleElement, people); parentNode.appendChild(peopleElement); }
From source file:org.eclipse.smila.connectivity.framework.crawler.web.parse.html.DOMBuilder.java
/** * Append a node to the current container. * /* w w w .ja v a 2 s . c o m*/ * @param newNode * New node to append * * @throws SAXException * the SAX exception */ protected void append(final Node newNode) throws org.xml.sax.SAXException { final Node currentNode = m_currentNode; if (null != currentNode) { currentNode.appendChild(newNode); } else if (null != m_docFrag) { m_docFrag.appendChild(newNode); } else { boolean ok = true; final short type = newNode.getNodeType(); if (type == Node.TEXT_NODE) { final String data = newNode.getNodeValue(); if ((null != data) && (data.trim().length() > 0)) { throw new org.xml.sax.SAXException( "Warning: can't output text before document element! Ignoring..."); } ok = false; } else if (type == Node.ELEMENT_NODE) { if (m_doc.getDocumentElement() != null) { throw new org.xml.sax.SAXException("Can't have more than one root on a DOM!"); } } if (ok) { m_doc.appendChild(newNode); } } }
From source file:org.eclipse.swordfish.p2.internal.deploy.server.MetadataProcessor.java
/** * Append a child node to an owner node/*w w w. j a v a 2 s . c o m*/ * @param parent - the parent node * @param childName - the name of the child node * @return the child node that was added */ private final Element appendChild(Node parent, String childName) { Element e = parent.getOwnerDocument().createElement(childName); parent.appendChild(e); return e; }
From source file:org.energy_home.jemma.ah.internal.configurator.Configuratore.java
protected void setTextContent(Document doc, Node node, String text) { Text textNode = doc.createTextNode(text); node.appendChild(textNode); }
From source file:org.energy_home.jemma.ah.internal.hac.lib.HacService.java
private void setTextContent(Document doc, Node node, String text) { Text textNode = doc.createTextNode(text); node.appendChild(textNode); }