List of usage examples for org.w3c.dom Element setAttributeNodeNS
public Attr setAttributeNodeNS(Attr newAttr) throws DOMException;
From source file:Main.java
public static void main(String[] args) throws Exception { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true);/*from www. j ava 2 s .co m*/ DocumentBuilder db = dbf.newDocumentBuilder(); File file1 = new File("input1.xml"); Document doc1 = db.parse(file1); Element rootElement1 = doc1.getDocumentElement(); File file2 = new File("input2.xml"); Document doc2 = db.parse(file2); Element rootElement2 = doc2.getDocumentElement(); // Copy Child Nodes NodeList childNodes2 = rootElement2.getChildNodes(); for (int x = 0; x < childNodes2.getLength(); x++) { Node importedNode = doc1.importNode(childNodes2.item(x), true); if (importedNode.getNodeType() == Node.ELEMENT_NODE) { Element importedElement = (Element) importedNode; // Copy Attributes NamedNodeMap namedNodeMap2 = rootElement2.getAttributes(); for (int y = 0; y < namedNodeMap2.getLength(); y++) { Attr importedAttr = (Attr) doc1.importNode(namedNodeMap2.item(y), true); importedElement.setAttributeNodeNS(importedAttr); } } rootElement1.appendChild(importedNode); } // Output Document TransformerFactory tf = TransformerFactory.newInstance(); Transformer t = tf.newTransformer(); DOMSource source = new DOMSource(doc1); StreamResult result = new StreamResult(System.out); t.transform(source, result); }
From source file:Main.java
public static void main(String[] args) throws Exception { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true);/* w w w. j a v a 2 s . c o m*/ DocumentBuilder db = dbf.newDocumentBuilder(); File file1 = new File("input1.xml"); Document doc1 = db.parse(file1); Element rootElement1 = doc1.getDocumentElement(); File file2 = new File("input2.xml"); Document doc2 = db.parse(file2); Element rootElement2 = doc2.getDocumentElement(); // Copy Attributes NamedNodeMap namedNodeMap2 = rootElement2.getAttributes(); for (int x = 0; x < namedNodeMap2.getLength(); x++) { Attr importedNode = (Attr) doc1.importNode(namedNodeMap2.item(x), true); rootElement1.setAttributeNodeNS(importedNode); } // Copy Child Nodes NodeList childNodes2 = rootElement2.getChildNodes(); for (int x = 0; x < childNodes2.getLength(); x++) { Node importedNode = doc1.importNode(childNodes2.item(x), true); rootElement1.appendChild(importedNode); } // Output Document TransformerFactory tf = TransformerFactory.newInstance(); Transformer t = tf.newTransformer(); DOMSource source = new DOMSource(doc1); StreamResult result = new StreamResult(System.out); t.transform(source, result); }
From source file:Main.java
/** * Add the first node with a namespace attribute as below: * <asset xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> * @nodeName: name of the element/*from ww w .j ava 2 s. c o m*/ * @ * */ public static Document addNodeWithNSAttribute(Document document, String nodeName, String attrName, String namespace) { Element node = document.createElement(nodeName); Attr attr = document.createAttribute(attrName); attr.setValue(namespace); node.setAttributeNodeNS(attr); document.appendChild(node); return document; }
From source file:Main.java
private static void transferAttributes(Element elm, Element elm2) { NamedNodeMap attributes = elm.getAttributes(); for (int c = 0; c < attributes.getLength(); c++) { Attr attr = (Attr) attributes.item(c); elm2.setAttributeNodeNS((Attr) elm2.getOwnerDocument().importNode(attr, true)); }//from w ww . j a v a 2s .co m }
From source file:cc.siara.csv_ml.ParsedObject.java
/** * Performas any pending activity against an element to finalize it. In this * case, it adds any pending attributes needing namespace mapping. * // ww w. j a va2 s. c o m * Also if the node has a namespace attached, it recreates the node with * specific URI. */ public void finalizeElement() { // Add all remaining attributes for (String col_name : pendingAttributes.keySet()) { String value = pendingAttributes.get(col_name); int cIdx = col_name.indexOf(':'); String ns = col_name.substring(0, cIdx); String nsURI = nsMap.get(ns); if (nsURI == null) nsURI = generalNSURI; Attr attr = doc.createAttributeNS(nsURI, col_name.substring(cIdx + 1)); attr.setPrefix(ns); attr.setValue(value); ((Element) cur_element).setAttributeNodeNS(attr); } // If the element had a namespace prefix, it has to be recreated. if (!currentElementNS.equals("") && !doc.getDocumentElement().equals(cur_element)) { Node parent = cur_element.getParentNode(); Element cur_ele = (Element) parent.removeChild(cur_element); String node_name = cur_ele.getNodeName(); String nsURI = nsMap.get(currentElementNS); if (nsURI == null) nsURI = generalNSURI; Element new_node = doc.createElementNS(nsURI, currentElementNS + ":" + node_name); parent.appendChild(new_node); // Add all attributes NamedNodeMap attrs = cur_ele.getAttributes(); while (attrs.getLength() > 0) { Attr attr = (Attr) attrs.item(0); cur_ele.removeAttributeNode(attr); nsURI = attr.getNamespaceURI(); new_node.setAttributeNodeNS(attr); } // Add all CData sections NodeList childNodes = cur_ele.getChildNodes(); for (int i = 0; i < childNodes.getLength(); i++) { Node node = childNodes.item(i); if (node.getNodeType() == Node.CDATA_SECTION_NODE) new_node.appendChild(node); } cur_element = new_node; } pendingAttributes = new Hashtable<String, String>(); }
From source file:com.fujitsu.dc.common.auth.token.TransCellAccessToken.java
/** * ?SAML????.//from www . j a v a2s .c om * @return SAML */ public String toSamlString() { /* * Creation of SAML2.0 Document * http://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf */ DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder builder = null; try { builder = dbf.newDocumentBuilder(); } catch (ParserConfigurationException e) { // ???????????? throw new RuntimeException(e); } Document doc = builder.newDocument(); Element assertion = doc.createElementNS(URN_OASIS_NAMES_TC_SAML_2_0_ASSERTION, "Assertion"); doc.appendChild(assertion); assertion.setAttribute("ID", this.id); assertion.setAttribute("Version", "2.0"); // Dummy Date DateTime dateTime = new DateTime(this.issuedAt); assertion.setAttribute("IssueInstant", dateTime.toString()); // Issuer Element issuer = doc.createElement("Issuer"); issuer.setTextContent(this.issuer); assertion.appendChild(issuer); // Subject Element subject = doc.createElement("Subject"); Element nameId = doc.createElement("NameID"); nameId.setTextContent(this.subject); Element subjectConfirmation = doc.createElement("SubjectConfirmation"); subject.appendChild(nameId); subject.appendChild(subjectConfirmation); assertion.appendChild(subject); // Conditions Element conditions = doc.createElement("Conditions"); Element audienceRestriction = doc.createElement("AudienceRestriction"); for (String aud : new String[] { this.target, this.schema }) { Element audience = doc.createElement("Audience"); audience.setTextContent(aud); audienceRestriction.appendChild(audience); } conditions.appendChild(audienceRestriction); assertion.appendChild(conditions); // AuthnStatement Element authnStmt = doc.createElement("AuthnStatement"); authnStmt.setAttribute("AuthnInstant", dateTime.toString()); Element authnCtxt = doc.createElement("AuthnContext"); Element authnCtxtCr = doc.createElement("AuthnContextClassRef"); authnCtxtCr.setTextContent("urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport"); authnCtxt.appendChild(authnCtxtCr); authnStmt.appendChild(authnCtxt); assertion.appendChild(authnStmt); // AttributeStatement Element attrStmt = doc.createElement("AttributeStatement"); Element attribute = doc.createElement("Attribute"); for (Role role : this.roleList) { Element attrValue = doc.createElement("AttributeValue"); Attr attr = doc.createAttributeNS("http://www.w3.org/2001/XMLSchema-instance", "type"); attr.setPrefix("xsi"); attr.setValue("string"); attrValue.setAttributeNodeNS(attr); attrValue.setTextContent(role.schemeCreateUrlForTranceCellToken(this.issuer)); attribute.appendChild(attrValue); } attrStmt.appendChild(attribute); assertion.appendChild(attrStmt); // Normalization doc.normalizeDocument(); // Dsig?? // Create a DOMSignContext and specify the RSA PrivateKey and // location of the resulting XMLSignature's parent element. DOMSignContext dsc = new DOMSignContext(privKey, doc.getDocumentElement()); // Create the XMLSignature, but don't sign it yet. XMLSignature signature = xmlSignatureFactory.newXMLSignature(signedInfo, keyInfo); // Marshal, generate, and sign the enveloped signature. try { signature.sign(dsc); // ? return DcCoreUtils.nodeToString(doc.getDocumentElement()); } catch (MarshalException e1) { // DOM??????? throw new RuntimeException(e1); } catch (XMLSignatureException e1) { // ?????????? throw new RuntimeException(e1); } /* * ------------------------------------------------------------ * http://tools.ietf.org/html/draft-ietf-oauth-saml2-bearer-10 * ------------------------------------------------------------ 2.1. Using SAML Assertions as Authorization * Grants To use a SAML Bearer Assertion as an authorization grant, use the following parameter values and * encodings. The value of "grant_type" parameter MUST be "urn:ietf:params:oauth:grant-type:saml2-bearer" The * value of the "assertion" parameter MUST contain a single SAML 2.0 Assertion. The SAML Assertion XML data MUST * be encoded using base64url, where the encoding adheres to the definition in Section 5 of RFC4648 [RFC4648] * and where the padding bits are set to zero. To avoid the need for subsequent encoding steps (by "application/ * x-www-form-urlencoded" [W3C.REC-html401-19991224], for example), the base64url encoded data SHOULD NOT be * line wrapped and pad characters ("=") SHOULD NOT be included. */ }
From source file:io.personium.common.auth.token.TransCellAccessToken.java
/** * ?SAML????.//from w w w . j a v a 2s. c om * @return SAML */ public String toSamlString() { /* * Creation of SAML2.0 Document * http://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf */ DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder builder = null; try { builder = dbf.newDocumentBuilder(); } catch (ParserConfigurationException e) { // ???????????? throw new RuntimeException(e); } Document doc = builder.newDocument(); Element assertion = doc.createElementNS(URN_OASIS_NAMES_TC_SAML_2_0_ASSERTION, "Assertion"); doc.appendChild(assertion); assertion.setAttribute("ID", this.id); assertion.setAttribute("Version", "2.0"); // Dummy Date DateTime dateTime = new DateTime(this.issuedAt); assertion.setAttribute("IssueInstant", dateTime.toString()); // Issuer Element issuer = doc.createElement("Issuer"); issuer.setTextContent(this.issuer); assertion.appendChild(issuer); // Subject Element subject = doc.createElement("Subject"); Element nameId = doc.createElement("NameID"); nameId.setTextContent(this.subject); Element subjectConfirmation = doc.createElement("SubjectConfirmation"); subject.appendChild(nameId); subject.appendChild(subjectConfirmation); assertion.appendChild(subject); // Conditions Element conditions = doc.createElement("Conditions"); Element audienceRestriction = doc.createElement("AudienceRestriction"); for (String aud : new String[] { this.target, this.schema }) { Element audience = doc.createElement("Audience"); audience.setTextContent(aud); audienceRestriction.appendChild(audience); } conditions.appendChild(audienceRestriction); assertion.appendChild(conditions); // AuthnStatement Element authnStmt = doc.createElement("AuthnStatement"); authnStmt.setAttribute("AuthnInstant", dateTime.toString()); Element authnCtxt = doc.createElement("AuthnContext"); Element authnCtxtCr = doc.createElement("AuthnContextClassRef"); authnCtxtCr.setTextContent("urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport"); authnCtxt.appendChild(authnCtxtCr); authnStmt.appendChild(authnCtxt); assertion.appendChild(authnStmt); // AttributeStatement Element attrStmt = doc.createElement("AttributeStatement"); Element attribute = doc.createElement("Attribute"); for (Role role : this.roleList) { Element attrValue = doc.createElement("AttributeValue"); Attr attr = doc.createAttributeNS("http://www.w3.org/2001/XMLSchema-instance", "type"); attr.setPrefix("xsi"); attr.setValue("string"); attrValue.setAttributeNodeNS(attr); attrValue.setTextContent(role.schemeCreateUrlForTranceCellToken(this.issuer)); attribute.appendChild(attrValue); } attrStmt.appendChild(attribute); assertion.appendChild(attrStmt); // Normalization doc.normalizeDocument(); // Dsig?? // Create a DOMSignContext and specify the RSA PrivateKey and // location of the resulting XMLSignature's parent element. DOMSignContext dsc = new DOMSignContext(privKey, doc.getDocumentElement()); // Create the XMLSignature, but don't sign it yet. XMLSignature signature = xmlSignatureFactory.newXMLSignature(signedInfo, keyInfo); // Marshal, generate, and sign the enveloped signature. try { signature.sign(dsc); // ? return PersoniumCoreUtils.nodeToString(doc.getDocumentElement()); } catch (MarshalException e1) { // DOM??????? throw new RuntimeException(e1); } catch (XMLSignatureException e1) { // ?????????? throw new RuntimeException(e1); } /* * ------------------------------------------------------------ * http://tools.ietf.org/html/draft-ietf-oauth-saml2-bearer-10 * ------------------------------------------------------------ 2.1. Using SAML Assertions as Authorization * Grants To use a SAML Bearer Assertion as an authorization grant, use the following parameter values and * encodings. The value of "grant_type" parameter MUST be "urn:ietf:params:oauth:grant-type:saml2-bearer" The * value of the "assertion" parameter MUST contain a single SAML 2.0 Assertion. The SAML Assertion XML data MUST * be encoded using base64url, where the encoding adheres to the definition in Section 5 of RFC4648 [RFC4648] * and where the padding bits are set to zero. To avoid the need for subsequent encoding steps (by "application/ * x-www-form-urlencoded" [W3C.REC-html401-19991224], for example), the base64url encoded data SHOULD NOT be * line wrapped and pad characters ("=") SHOULD NOT be included. */ }
From source file:org.alfresco.web.forms.xforms.Schema2XForms.java
@SuppressWarnings("unchecked") public static void rebuildInstance(final Node prototypeNode, final Node oldInstanceNode, final Node newInstanceNode, final HashMap<String, String> schemaNamespaces) { final JXPathContext prototypeContext = JXPathContext.newContext(prototypeNode); prototypeContext.registerNamespace(NamespaceService.ALFRESCO_PREFIX, NamespaceService.ALFRESCO_URI); final JXPathContext instanceContext = JXPathContext.newContext(oldInstanceNode); instanceContext.registerNamespace(NamespaceService.ALFRESCO_PREFIX, NamespaceService.ALFRESCO_URI); for (final String prefix : schemaNamespaces.keySet()) { prototypeContext.registerNamespace(prefix, schemaNamespaces.get(prefix)); instanceContext.registerNamespace(prefix, schemaNamespaces.get(prefix)); }//from w w w. j av a 2s . co m // Evaluate non-recursive XPaths for all prototype elements at this level final Iterator<Pointer> it = prototypeContext.iteratePointers("*"); while (it.hasNext()) { final Pointer p = it.next(); Element proto = (Element) p.getNode(); String path = p.asPath(); // check if this is a prototype element with the attribute set boolean isPrototype = proto.hasAttributeNS(NamespaceService.ALFRESCO_URI, "prototype") && proto.getAttributeNS(NamespaceService.ALFRESCO_URI, "prototype").equals("true"); // We shouldn't locate a repeatable child with a fixed path if (isPrototype) { path = path.replaceAll("\\[(\\d+)\\]", "[position() >= $1]"); if (LOGGER.isDebugEnabled()) { LOGGER.debug("[rebuildInstance] evaluating prototyped nodes " + path); } } else { if (LOGGER.isDebugEnabled()) { LOGGER.debug("[rebuildInstance] evaluating child node with positional path " + path); } } Document newInstanceDocument = newInstanceNode.getOwnerDocument(); // Locate the corresponding nodes in the instance document List<Node> l = (List<Node>) instanceContext.selectNodes(path); // If the prototype node isn't a prototype element, copy it in as a missing node, complete with all its children. We won't need to recurse on this node if (l.isEmpty()) { if (!isPrototype) { LOGGER.debug("[rebuildInstance] copying in missing node " + proto.getNodeName() + " to " + XMLUtil.buildXPath(newInstanceNode, newInstanceDocument.getDocumentElement())); // Clone the prototype node and all its children Element clone = (Element) proto.cloneNode(true); newInstanceNode.appendChild(clone); if (oldInstanceNode instanceof Document) { // add XMLSchema instance NS addNamespace(clone, NamespaceConstants.XMLSCHEMA_INSTANCE_PREFIX, NamespaceConstants.XMLSCHEMA_INSTANCE_NS); } } } else { // Otherwise, append the matches from the old instance document in order for (Node old : l) { Element oldEl = (Element) old; // Copy the old instance element rather than cloning it, so we don't copy over attributes Element clone = null; String nSUri = oldEl.getNamespaceURI(); if (nSUri == null) { clone = newInstanceDocument.createElement(oldEl.getTagName()); } else { clone = newInstanceDocument.createElementNS(nSUri, oldEl.getTagName()); } newInstanceNode.appendChild(clone); if (oldInstanceNode instanceof Document) { // add XMLSchema instance NS addNamespace(clone, NamespaceConstants.XMLSCHEMA_INSTANCE_PREFIX, NamespaceConstants.XMLSCHEMA_INSTANCE_NS); } // Copy over child text if this is not a complex type boolean isEmpty = true; for (Node n = old.getFirstChild(); n != null; n = n.getNextSibling()) { if (n instanceof Text) { clone.appendChild(newInstanceDocument.importNode(n, false)); isEmpty = false; } else if (n instanceof Element) { break; } } // Populate the nil attribute. It may be true or false if (proto.hasAttributeNS(NamespaceConstants.XMLSCHEMA_INSTANCE_NS, "nil")) { clone.setAttributeNS(NamespaceConstants.XMLSCHEMA_INSTANCE_NS, NamespaceConstants.XMLSCHEMA_INSTANCE_PREFIX + ":nil", String.valueOf(isEmpty)); } // Copy over attributes present in the prototype NamedNodeMap attributes = proto.getAttributes(); for (int i = 0; i < attributes.getLength(); i++) { Attr attribute = (Attr) attributes.item(i); String localName = attribute.getLocalName(); if (localName == null) { String name = attribute.getName(); if (oldEl.hasAttribute(name)) { clone.setAttributeNode( (Attr) newInstanceDocument.importNode(oldEl.getAttributeNode(name), false)); } else { LOGGER.debug("[rebuildInstance] copying in missing attribute " + attribute.getNodeName() + " to " + XMLUtil.buildXPath(clone, newInstanceDocument.getDocumentElement())); clone.setAttributeNode((Attr) attribute.cloneNode(false)); } } else { String namespace = attribute.getNamespaceURI(); if (!((!isEmpty && (namespace.equals(NamespaceConstants.XMLSCHEMA_INSTANCE_NS) && localName.equals("nil")) || (namespace.equals(NamespaceService.ALFRESCO_URI) && localName.equals("prototype"))))) { if (oldEl.hasAttributeNS(namespace, localName)) { clone.setAttributeNodeNS((Attr) newInstanceDocument .importNode(oldEl.getAttributeNodeNS(namespace, localName), false)); } else { LOGGER.debug("[rebuildInstance] copying in missing attribute " + attribute.getNodeName() + " to " + XMLUtil.buildXPath(clone, newInstanceDocument.getDocumentElement())); clone.setAttributeNodeNS((Attr) attribute.cloneNode(false)); } } } } // recurse on children rebuildInstance(proto, oldEl, clone, schemaNamespaces); } } // Now add in a new copy of the prototype if (isPrototype) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("[rebuildInstance] appending " + proto.getNodeName() + " to " + XMLUtil.buildXPath(newInstanceNode, newInstanceDocument.getDocumentElement())); } newInstanceNode.appendChild(proto.cloneNode(true)); } } }
From source file:org.apache.hadoop.gateway.filter.rewrite.impl.xml.XmlFilterReader.java
private Attr bufferAttribute(Element element, Attribute attribute) { QName name = attribute.getName(); String prefix = name.getPrefix(); String uri = name.getNamespaceURI(); Attr node;// w w w .ja va 2 s.com if (uri == null || uri.isEmpty()) { node = document.createAttribute(name.getLocalPart()); element.setAttributeNode(node); } else { node = document.createAttributeNS(uri, name.getLocalPart()); if (prefix != null && !prefix.isEmpty()) { node.setPrefix(prefix); } element.setAttributeNodeNS(node); } node.setTextContent(attribute.getValue()); return node; }
From source file:org.apache.hadoop.gateway.filter.rewrite.impl.xml.XmlFilterReader.java
private void streamAttribute(Element element, Attribute attribute) throws XPathExpressionException { Attr node;// ww w . ja va 2 s . com QName name = attribute.getName(); String prefix = name.getPrefix(); String uri = name.getNamespaceURI(); if (uri == null || uri.isEmpty()) { node = document.createAttribute(name.getLocalPart()); element.setAttributeNode(node); } else { node = document.createAttributeNS(uri, name.getLocalPart()); if (prefix != null && !prefix.isEmpty()) { node.setPrefix(prefix); } element.setAttributeNodeNS(node); } String value = attribute.getValue(); Level level = stack.peek(); if ((level.scopeConfig) == null || (level.scopeConfig.getSelectors().isEmpty())) { value = filterAttribute(null, attribute.getName(), value, null); node.setValue(value); } else { UrlRewriteFilterPathDescriptor path = pickFirstMatchingPath(level); if (path instanceof UrlRewriteFilterApplyDescriptor) { String rule = ((UrlRewriteFilterApplyDescriptor) path).rule(); value = filterAttribute(null, attribute.getName(), value, rule); node.setValue(value); } } //dump( document ); if (prefix == null || prefix.isEmpty()) { writer.write(" "); writer.write(name.getLocalPart()); } else { writer.write(" "); writer.write(prefix); writer.write(":"); writer.write(name.getLocalPart()); } writer.write("=\""); writer.write(value); writer.write("\""); element.removeAttributeNode(node); }