List of usage examples for org.w3c.dom Node hasAttributes
public boolean hasAttributes();
From source file:psidev.psi.mi.filemakers.xsd.AbstractXsdTreeStruct.java
protected void print(Node node) { try {//from w ww. ja va 2 s .c om log.debug("attributes:"); if (node.hasAttributes()) { for (int i = 0; i < node.getAttributes().getLength(); i++) { log.debug(node.getAttributes().item(i).getNodeName() + "; " + node.getAttributes().item(i).getNodeValue()); } } log.debug("chidren:"); for (int i = 0; i < node.getChildNodes().getLength(); i++) { log.debug(node.getChildNodes().item(i).getNodeName() + "; " + node.getChildNodes().item(i).getNodeValue()); print(node.getChildNodes().item(i)); } } catch (Exception e) { log.error(e); } }
From source file:psidev.psi.mi.filemakers.xsd.AbstractXsdTreeStruct.java
/** * the name of an element in the schema is contained in the attribute 'name' * * @param node//from www.java2 s .c o m * @return */ private String getName(Node node) { if (node.hasAttributes() == false) { return null; } for (int i = 0; i < node.getAttributes().getLength(); i++) { if (node.getAttributes().item(i).getNodeName().equals("name")) { return node.getAttributes().item(i).getNodeValue(); } } return null; }
From source file:tds.websim.presentation.services.WebSimXHR.java
private String getTestKey(Document doc) { String testKey = null;/*from w ww .ja v a 2 s . com*/ Element elem = doc.getDocumentElement(); if (elem != null) { Node node = SimPubSession.getXmlNodeChild(elem, "identifier"); if (node != null && node.hasAttributes()) { Node attr = node.getAttributes().getNamedItem("uniqueid"); if (attr != null) testKey = attr.getNodeValue(); } } return testKey; }
From source file:test.framework.TestBase.java
/** * Return the text value of the selected attribute NOT considering namespaces. * //from www . j a v a2 s. c om * @param node The node. * @param xPath The xpath to select the node containing the attribute. * @param attributeName The name of the attribute. * @return The text value of the selected attribute. * @throws Exception If anything fails. */ protected static String getAttributeValue(final Node node, final String xPath, final String attributeName) throws Exception { String result = null; Node singleNode = selectSingleNode(node, xPath); if (singleNode == null) { throw new Exception("Single node for path '" + xPath + "' not found."); } if (singleNode.hasAttributes()) { result = singleNode.getAttributes().getNamedItem(attributeName).getTextContent(); } return result; }
From source file:test.framework.TestBase.java
/** * Return the text value of the selected attribute considering namespaces. * // w w w . j a v a 2 s . c o m * @param node The node. * @param xPath The xpath to select the node containing the attribute. * @param attributeNamespaceURI The namespace URI of the attribute. * @param attributeLocalName The local name of the attribute. * @return The value for the given attribute. * @throws Exception */ protected static String getAttributeValueNS(final Node node, final String xPath, final String attributeNamespaceURI, final String attributeLocalName) throws Exception { String result = null; NodeList nodeList = selectNodeList(node, xPath); assertTrue(nodeList.getLength() == 1); Node hitNode = nodeList.item(0); if (hitNode.hasAttributes()) { NamedNodeMap nnm = hitNode.getAttributes(); Node attrNode = nnm.getNamedItemNS(attributeNamespaceURI, attributeLocalName); result = attrNode.getTextContent(); } return result; }
From source file:tufts.vue.ds.XMLIngest.java
private static void scanNode(final XmlSchema schema, final org.w3c.dom.Node node, final int type, final String parentPath, final String parentName, final String nodeName, final String value) { final boolean isAttribute = (type == Node.ATTRIBUTE_NODE); final boolean isMergedText = FOLD_TEXT && isText(type); final boolean hasAttributes = (!isAttribute && node != null && node.hasAttributes()); Node firstChild = null, lastChild = null; if (node != null) { firstChild = node.getFirstChild(); lastChild = node.getLastChild(); }/*from w w w.ja v a 2 s .com*/ final String XMLName; if (isAttribute) XMLName = parentName + ATTR_SEPARATOR + nodeName; else XMLName = nodeName; final String fullName; if (parentPath != null) { // should only be null first time in at the top root if (isMergedText) fullName = parentPath; else if (isAttribute) fullName = parentPath + ATTR_SEPARATOR + nodeName; else fullName = parentPath + '.' + nodeName; } else { fullName = nodeName; } if (type == Node.ELEMENT_NODE) schema.trackNodeOpen(fullName); if (depth < REPORT_THRESH) { if (depth < REPORT_THRESH - 1) { if (type == Node.TEXT_NODE) eoutln(String.format("node(%s) {%s} (len=%d)", getNodeType(type), fullName, value.length())); else eoutln(String.format("NODE(%s) {%s} %.192s", getNodeType(type), fullName, node, Util.tags(firstChild))); } //eoutln("NODE: " + type + " name=" + name + " " + Util.tags(n) + " firstChild=" + Util.tags(firstChild)); //System.err.println(name); else if (XML_DEBUG) System.err.print("."); } if (hasAttributes && ATTRIBUTES_IMMEDIATE) scanAttributes(schema, fullName, nodeName, node.getAttributes()); String outputValue = null; if (value != null) { outputValue = value.trim(); if (outputValue.length() > 0) { schema.trackFieldValuePair(fullName, outputValue); } else outputValue = null; } final NodeList children = node == null ? null : node.getChildNodes(); final boolean DO_TAG; if (isMergedText) { DO_TAG = false; } else if (outputValue == null && node != null) { if (!node.hasChildNodes()) { DO_TAG = false; } else if (children.getLength() == 1 && isText(firstChild) && firstChild.getNodeValue().trim().length() == 0) { DO_TAG = false; } else DO_TAG = true; // if (!DO_TAG) ioutln("<!-- empty: " + nodeName + " -->"); } else DO_TAG = true; boolean closeOnSameLine = false; if (DO_TAG) { iout("<"); out(XMLName); //if (node.hasChildNodes()) out(" children=" + node.getChildNodes().getLength() + " first=" + node.getFirstChild()); out(">"); if (firstChild == null || (isText(firstChild) && firstChild == lastChild)) { // if (firstChild != null && firstChild.getNodeType() == Node.CDATA_SECTION_NODE) // ; // else closeOnSameLine = true; } else if (XML_OUTPUT) System.out.print('\n'); if (FOLD_TEXT && (type != Node.ELEMENT_NODE && type != Node.ATTRIBUTE_NODE)) { final String err = "UNHANDLED TYPE=" + type + "; " + nodeName; outln("<" + err + ">"); errout(err); } } if (outputValue != null) { if (type == Node.CDATA_SECTION_NODE) { out("<![CDATA["); out(outputValue); out("]]>"); } else { out(XMLEntityEncode(outputValue)); } } if (!isAttribute && node != null) { // god knows why, but attributes have themselves as children? (or is that // the #text entry?) Anyway, if we allow this for an attribute dump, the // value of the attribute will literally appear twice in the output, // back-to-back as one string. depth++; if (FOLD_KEYS || schema.isXMLKeyFold()) { scanFoldedChildren(schema, children, fullName, nodeName); } else { for (int i = 0; i < children.getLength(); i++) scanNode(schema, children.item(i), fullName, nodeName); } depth--; } if (DO_TAG) { if (closeOnSameLine) outln("</" + XMLName + ">"); else ioutln("</" + XMLName + ">"); } if (type == Node.ELEMENT_NODE) schema.trackNodeClose(fullName); if (hasAttributes && !ATTRIBUTES_IMMEDIATE) scanAttributes(schema, fullName, nodeName, node.getAttributes()); //iout("children: " + Util.tags(n.getChildNodes())); }
From source file:ua.utility.kfsdbupgrade.MaintainableXMLConversionServiceImpl.java
/** * Transforms the given <code>xml</code> section from KFS3 format to KFS6 * format.//w w w. java 2s . com * * @param xml * {@link String} of the XML to transform * @return {@link String} of the transformed XML * @throws Exception * Any {@link Exception}s encountered will be rethrown. */ private String transformSection(String xml, String docid) throws Exception { String rawXml = xml; String maintenanceAction = StringUtils.substringBetween(xml, "<" + MAINTENANCE_ACTION_ELEMENT_NAME + ">", "</" + MAINTENANCE_ACTION_ELEMENT_NAME + ">"); xml = StringUtils.substringBefore(xml, "<" + MAINTENANCE_ACTION_ELEMENT_NAME + ">"); xml = upgradeBONotes(xml, docid); if (classNameRuleMap == null) { setRuleMaps(); } DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document document; try { document = db.parse(new InputSource(new StringReader(xml))); } catch (SAXParseException ex) { String eol = System.getProperty("line.separator"); String exMsg = "Failed in db.parse(new InputSource(new StringReader(xml))) where xml=" + xml + eol + "of maintenanceAction = " + maintenanceAction + eol + "contained in rawXml = " + rawXml; throw new SAXParseException(exMsg, null, ex); } for (Node childNode = document.getFirstChild(); childNode != null;) { Node nextChild = childNode.getNextSibling(); transformClassNode(document, childNode); // Also Transform first level Children which have class attribute NodeList children = childNode.getChildNodes(); for (int n = 0; n < children.getLength(); n++) { Node child = children.item(n); if ((child != null) && (child.getNodeType() == Node.ELEMENT_NODE) && (child.hasAttributes())) { NamedNodeMap childAttributes = child.getAttributes(); if (childAttributes.item(0).getNodeName() == "class") { String childClassName = childAttributes.item(0).getNodeValue(); if (classPropertyRuleMap.containsKey(childClassName)) { Map<String, String> propertyMappings = classPropertyRuleMap.get(childClassName); NodeList nestedChildren = child.getChildNodes(); for (int i = 0; i < nestedChildren.getLength() - 1; i++) { Node property = nestedChildren.item(i); String propertyName = property.getNodeName(); if ((property.getNodeType() == Node.ELEMENT_NODE) && (propertyMappings != null) && (propertyMappings.containsKey(propertyName))) { String newPropertyName = propertyMappings.get(propertyName); if (StringUtils.isNotBlank(newPropertyName)) { document.renameNode(property, null, newPropertyName); propertyName = newPropertyName; } else { // If there is no replacement name then the element needs to be removed child.removeChild(property); } } } } } } } childNode = nextChild; } /* * the default logic that traverses over the document tree doesn't * handle classes that are in an @class attribute, so we deal with those * individually. */ migratePersonObjects(document); migrateKualiCodeBaseObjects(document); migrateAccountExtensionObjects(document); migrateClassAsAttribute(document); removeAutoIncrementSetElements(document); removeReconcilerGroup(document); catchMissedTypedArrayListElements(document); TransformerFactory transFactory = TransformerFactory.newInstance(); Transformer trans = transFactory.newTransformer(); trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); trans.setOutputProperty(OutputKeys.INDENT, "yes"); StringWriter writer = new StringWriter(); StreamResult result = new StreamResult(writer); DOMSource source = new DOMSource(document); trans.transform(source, result); /* * (?m) puts the regex into multiline mode: * https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern. * html#MULTILINE So the effect of this statement is * "remove any empty lines" */ xml = writer.toString().replaceAll("(?m)^\\s+\\n", ""); xml = xml + "<" + MAINTENANCE_ACTION_ELEMENT_NAME + ">" + maintenanceAction + "</" + MAINTENANCE_ACTION_ELEMENT_NAME + ">"; // replace classnames not updated so far that were captured by smoke test below // Using context specific replacements in case match replacement pairs entered are too generic for (String className : classNameRuleMap.keySet()) { if (xml.contains("active defined-in=\"" + className + "\"")) { LOGGER.info("Replacing active defined-in= attribute: " + className + " with: " + classNameRuleMap.get(className) + " at docid= " + docid); xml = xml.replace("active defined-in=\"" + className + "\"", "active defined-in=\"" + classNameRuleMap.get(className) + "\""); } } // Using context specific replacements in case match replacement pairs entered are too generic for (String className : classNameRuleMap.keySet()) { if (xml.contains("<" + className + ">")) { LOGGER.info("Replacing open tag: <" + className + "> with: <" + classNameRuleMap.get(className) + ">" + " at docid= " + docid); xml = xml.replace("<" + className + ">", "<" + classNameRuleMap.get(className) + ">"); } } // Using context specific replacements in case match replacement pairs entered are too generic for (String className : classNameRuleMap.keySet()) { if (xml.contains("</" + className + ">")) { LOGGER.info("Replacing close tag: </" + className + "> with: </" + classNameRuleMap.get(className) + ">" + " at docid= " + docid); xml = xml.replace("</" + className + ">", "</" + classNameRuleMap.get(className) + ">"); } } // replace classnames not updated so far that were captured by smoke test below // Using context specific replacements in case match replacement pairs entered are too generic for (String className : classNameRuleMap.keySet()) { if (xml.contains("maintainableImplClass=\"" + className + "\"")) { LOGGER.info("Replacing maintainableImplClass= attribute: " + className + " with: " + classNameRuleMap.get(className) + " at docid= " + docid); xml = xml.replace("maintainableImplClass=\"" + className + "\"", "maintainableImplClass=\"" + classNameRuleMap.get(className) + "\""); } } // investigative logging, still useful as a smoke test for (String oldClassName : classNameRuleMap.keySet()) { if (xml.contains(oldClassName)) { LOGGER.warn("Document has classname in contents that should have been mapped: " + oldClassName); LOGGER.warn("at docid= " + docid + " for xml= " + xml); } } checkForElementsWithClassAttribute(document); return xml; }
From source file:us.conxio.hl7.hl7service.Operand.java
/** * Constructs a HL7MessageTransformOperation for the argument xml Node. * @param node The node from which to construct the object. * @throws IOException If the file is not found, or is not properly formatted. *//* w w w . j a v a 2s . c o m*/ public HL7MessageTransformOperation(Node node) throws IOException { opName = node.getNodeName().toLowerCase(); if (!haveThisMethod()) { logger.error("Not a valid method:" + opName); return; } // if if (node.hasAttributes()) { AttributeMap attributes = new AttributeMap(node); if (attributes.hasKey(OPERAND_TYPE_DESIGNATOR)) { resultDesignator = attributes.get(OPERAND_TYPE_DESIGNATOR); } // if if (attributes.hasKey(OPERAND_TYPE_SEARCH)) { _addOperand(new Operand(OPERAND_TYPE_SEARCH, attributes.get(OPERAND_TYPE_SEARCH))); } // if if (attributes.hasKey(OPERAND_TYPE_RESOURCE)) { initializeMap(attributes.get(OPERAND_TYPE_RESOURCE)); } // if } // if String nodeText = node.getTextContent(); if (StringUtils.isNotEmpty(nodeText)) { String[] operandsArray = nodeText.split(", ?", -2); int opsLength = operandsArray.length; for (int index = 0; index < opsLength; ++index) { _addOperand(new Operand(OPERAND_TYPE_STRING, operandsArray[index])); } // for } // if }
From source file:us.conxio.hl7.hl7service.HL7ServiceElement.java
/** * Finds and returns the attribute value corresponding to the argument attribute name, for the argument * element node./*from w ww. j av a2s . c o m*/ * @param elementNode The element node in which to seek the argument attribute. * @param attributeName The name of the attribute sought. * @return The sought attribute value, if found. */ public String getAttribute(Node elementNode, String attributeName) { if (elementNode == null) return null; if (!elementNode.hasAttributes()) return null; AttributeMap map = AttributeMap.getAttributes(elementNode); if (map != null) return map.get(attributeName.toLowerCase()); return null; }
From source file:us.conxio.XMLUtilities.AttributeMap.java
private void _getAttributes(Node node) { if (node == null) return;/*from w w w . j a v a2 s . c o m*/ if (!node.hasAttributes()) return; NamedNodeMap attribs = node.getAttributes(); int attribCount = attribs.getLength(); for (int index = 0; index < attribCount; ++index) { Node attribNode = attribs.item(index); String attribName = attribNode.getNodeName().toLowerCase(); _add(attribName, attribNode.getNodeValue()); } // for }