List of usage examples for org.w3c.dom Attr setTextContent
public void setTextContent(String textContent) throws DOMException;
From source file:cz.muni.fi.mir.mathmlunificator.MathMLUnificatorCommandLineTool.java
/** * Main (starting) method of the command line application. * * @param argv Array of command line arguments that are expected to be * filesystem paths to input XML documents with MathML to be unified. * @throws ParserConfigurationException If a XML DOM builder cannot be * created with the configuration requested. *//*w w w. j av a 2 s. c o m*/ public static void main(String argv[]) throws ParserConfigurationException { final Options options = new Options(); options.addOption("p", "operator-unification", false, "unify operator in addition to other types of nodes"); options.addOption("h", "help", false, "print help"); final CommandLineParser parser = new DefaultParser(); CommandLine line = null; try { line = parser.parse(options, argv); } catch (ParseException ex) { printHelp(options); System.exit(1); } if (line != null) { if (line.hasOption('h')) { printHelp(options); System.exit(0); } operatorUnification = line.hasOption('p'); final List<String> arguments = Arrays.asList(line.getArgs()); if (arguments.size() > 0) { Document outerDocument = DOMBuilder.getDocumentBuilder().newDocument(); Node rootNode = outerDocument.createElementNS(UNIFIED_MATHML_NS, UNIFIED_MATHML_NS_PREFIX + ":" + UNIFIED_MATHML_BATCH_OUTPUT_ROOT_ELEM); outerDocument.appendChild(rootNode); for (String filepath : arguments) { try { Document doc = DOMBuilder.buildDocFromFilepath(filepath); MathMLUnificator.unifyMathML(doc, operatorUnification); if (arguments.size() == 1) { xmlStdoutSerializer(doc); } else { Node itemNode = rootNode.getOwnerDocument().createElementNS(UNIFIED_MATHML_NS, UNIFIED_MATHML_NS_PREFIX + ":" + UNIFIED_MATHML_BATCH_OUTPUT_ITEM_ELEM); Attr filenameAttr = itemNode.getOwnerDocument().createAttributeNS(UNIFIED_MATHML_NS, UNIFIED_MATHML_NS_PREFIX + ":" + UNIFIED_MATHML_BATCH_OUTPUT_ITEM_FILEPATH_ATTR); filenameAttr.setTextContent(String.valueOf(filepath)); ((Element) itemNode).setAttributeNodeNS(filenameAttr); itemNode.appendChild( rootNode.getOwnerDocument().importNode(doc.getDocumentElement(), true)); rootNode.appendChild(itemNode); } } catch (SAXException | IOException ex) { Logger.getLogger(MathMLUnificatorCommandLineTool.class.getName()).log(Level.SEVERE, "Failed processing of file: " + filepath, ex); } } if (rootNode.getChildNodes().getLength() > 0) { xmlStdoutSerializer(rootNode.getOwnerDocument()); } } else { printHelp(options); System.exit(0); } } }
From source file:Main.java
public static Attr createAttribute(Document document, String name, String value) { Attr attr = document.createAttribute(name); attr.setTextContent(value); return attr;/* w ww .ja v a2 s . c o m*/ }
From source file:Main.java
public static void appendStringAttribute(Element thisElem, String attrName, String attrValue) { Attr attr = thisElem.getOwnerDocument().createAttribute(attrName); attr.setTextContent(attrValue); thisElem.setAttributeNode(attr);/*from www.j a va2 s . c om*/ }
From source file:fr.fastconnect.factory.tibco.bw.maven.compile.ArchiveBuilder.java
protected void setAttribute(ElementNSImpl element, String attributeName, String textContent) { if (element != null) { Attr attribute = element.getAttributeNode(attributeName); if (attribute != null) { attribute.setTextContent(textContent); }// ww w . j a va 2 s . c o m } }
From source file:edu.lternet.pasta.datapackagemanager.LevelOneEMLFactory.java
private void modifyAccessElementAttributes(Document emlDocument) throws TransformerException { CachedXPathAPI xpathapi = new CachedXPathAPI(); // Parse the access elements NodeList accessNodeList = xpathapi.selectNodeList(emlDocument, ACCESS_PATH); if (accessNodeList != null) { for (int i = 0; i < accessNodeList.getLength(); i++) { boolean hasSystemAttribute = false; Element accessElement = (Element) accessNodeList.item(i); NamedNodeMap accessAttributesList = accessElement.getAttributes(); for (int j = 0; j < accessAttributesList.getLength(); j++) { Node attributeNode = accessAttributesList.item(j); String nodeName = attributeNode.getNodeName(); String nodeValue = attributeNode.getNodeValue(); if (nodeName.equals("authSystem")) { attributeNode.setNodeValue(LEVEL_ONE_AUTH_SYSTEM_ATTRIBUTE); } else if (nodeName.equals("system")) { attributeNode.setNodeValue(LEVEL_ONE_SYSTEM_ATTRIBUTE); hasSystemAttribute = true; }//from w ww . ja v a 2 s .com } /* * No @system attribute was found in the access element, so we * need to add one. */ if (!hasSystemAttribute) { Attr systemAttribute = emlDocument.createAttribute("system"); systemAttribute.setTextContent(LEVEL_ONE_SYSTEM_ATTRIBUTE); accessElement.setAttributeNode(systemAttribute); } } } }
From source file:cz.muni.fi.mir.mathmlunificator.MathMLUnificator.java
/** * <p>// ww w . j a v a 2 s. co m * Implementation of MathML unification. In the given W3C DOM represented * XML document find all maths nodes (see * {@link DocumentParser#findMathMLNodes(org.w3c.dom.Document)}) and * remember links to operator elements and other elements in * {@link #nodesByDepth} data structure. Then substitute them gradualy for * series of formulae with leaf elements substituted for a special * unification representing symbol {@code ◍} (for Presentation * MathML, see {@link Constants#PMATHML_UNIFICATOR}) or {@code ◐} * (for Content MathML, see {@link Constants#CMATHML_UNIFICATOR}). * </p> * <p> * Resulting series of the original and unified MathML nodes is itself * encapsulated in a new element <unified-math> (see * {@link Constants#UNIFIED_MATHML_ROOT_ELEM}) in XML namespace * <code>http://mir.fi.muni.cz/mathml-unification/</code> (see * {@link Constants#UNIFIED_MATHML_NS}) and put to the place of the original * math element {@link Node} in the XML DOM representation the node is * attached to. * </p> * * @param mathNode W3C DOM XML document representation attached MathML node * to work on. * @param workInPlace If <code>true</code>, given <code>mathNode</code> will * be modified in place; if <code>false</code>, <code>mathNode</code> will * not be modified and series of modified nodes will be returned. * @param operatorUnification If <code>true</code> unify also operator * nodes, otherwise keep operator nodes intact. * @return <code>null</code> if <code>workInPlace</code> is * <code>false</code>; otherwise collection of unified versions of the * <code>mathNode</code> with key of the {@link HashMap} describing order * (level of unification) of elements in the collection. */ private HashMap<Integer, Node> unifyMathMLNodeImpl(Node mathNode, boolean operatorUnification, boolean workInPlace) { if (mathNode.getOwnerDocument() == null) { String msg = "The given node is not attached to any document."; if (mathNode.getNodeType() == Node.DOCUMENT_NODE) { msg = "The given node is document itself. Call with mathNode.getDocumentElement() instead."; } throw new IllegalArgumentException(msg); } nodesByDepth = new HashMap<>(); Node unifiedMathNode = null; HashMap<Integer, Node> unifiedNodesList = null; Document unifiedMathDoc = null; if (workInPlace) { // New element encapsulating the series of unified formulae. unifiedMathNode = mathNode.getOwnerDocument().createElementNS(UNIFIED_MATHML_NS, UNIFIED_MATHML_ROOT_ELEM); mathNode.getParentNode().replaceChild(unifiedMathNode, mathNode); unifiedMathNode.appendChild(mathNode.cloneNode(true)); } else { unifiedNodesList = new HashMap<>(); // Create a new separate DOM to work over with imporeted clone of the node given by user unifiedMathDoc = DOMBuilder.createNewDocWithNodeClone(mathNode, true); mathNode = unifiedMathDoc.getDocumentElement(); } // Parse XML subtree starting at mathNode and remember elements by their depth. rememberLevelsOfNodes(mathNode, operatorUnification); // Build series of formulae of level by level unified MathML. NodeLevel<Integer, Integer> level = new NodeLevel<>(getMaxMajorNodesLevel(), NUMOFMINORLEVELS); int levelAttrCounter = 0; Collection<Attr> maxLevelAttrs = new LinkedList<>(); while (level.major > 0) { if (nodesByDepth.containsKey(level)) { if (unifyAtLevel(level)) { levelAttrCounter++; Node thisLevelMathNode = mathNode.cloneNode(true); Attr thisLevelAttr = thisLevelMathNode.getOwnerDocument().createAttributeNS(UNIFIED_MATHML_NS, UNIFIED_MATHML_NS_PREFIX + ":" + UNIFIED_MATHML_LEVEL_ATTR); Attr maxLevelAttr = thisLevelMathNode.getOwnerDocument().createAttributeNS(UNIFIED_MATHML_NS, UNIFIED_MATHML_NS_PREFIX + ":" + UNIFIED_MATHML_MAX_LEVEL_ATTR); maxLevelAttrs.add(maxLevelAttr); thisLevelAttr.setTextContent(String.valueOf(levelAttrCounter)); ((Element) thisLevelMathNode).setAttributeNodeNS(thisLevelAttr); ((Element) thisLevelMathNode).setAttributeNodeNS(maxLevelAttr); if (workInPlace) { unifiedMathNode.appendChild(thisLevelMathNode); } else { // Create a new document for every node in the collection. unifiedNodesList.put(levelAttrCounter, DOMBuilder.cloneNodeToNewDoc(thisLevelMathNode, true)); } } } level.minor--; if (level.minor <= 0) { level.major--; level.minor = NUMOFMINORLEVELS; } } for (Attr attr : maxLevelAttrs) { attr.setTextContent(String.valueOf((levelAttrCounter))); } if (workInPlace) { return null; } else { for (Node node : unifiedNodesList.values()) { Attr maxLevelAttr = (Attr) node.getAttributes().getNamedItemNS(UNIFIED_MATHML_NS, UNIFIED_MATHML_MAX_LEVEL_ATTR); if (maxLevelAttr != null) { maxLevelAttr.setTextContent(String.valueOf((levelAttrCounter))); } } return unifiedNodesList; } }
From source file:de.escidoc.core.test.EscidocTestBase.java
/** * Creates a new attribute node for the provided document. * /*from w ww. java 2s . c o m*/ * @param doc * The document for that the node shall be created. * @param namespaceUri * The name space uri of the node to create. This may be null. * @param prefix * The prefix to use. * @param tagName * The tag name of the node. * @param value * The attribute value. * @return Returns the created node. * @throws Exception * Thrown if anything fails. */ public static Attr createAttributeNode(final Document doc, final String namespaceUri, final String prefix, final String tagName, final String value) throws Exception { Attr newAttribute = doc.createAttributeNS(namespaceUri, tagName); newAttribute.setPrefix(prefix); newAttribute.setValue(value); if (value != null) { newAttribute.setTextContent(value); } return newAttribute; }
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; if (uri == null || uri.isEmpty()) { node = document.createAttribute(name.getLocalPart()); element.setAttributeNode(node);/*from w w w. j a v a 2 s . c o m*/ } 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.ojbc.util.xml.XmlUtils.java
/** * Add an attribute to the specified element * @param parent the element to which we add the attribute * @param ns the namespace of the attribute * @param attributeName the name of the attribute * @param value the value of the attribute * @return the attribute// www . jav a 2 s .c om */ public static final Attr addAttribute(Element parent, String ns, String attributeName, String value) { Document doc = parent.getOwnerDocument(); Attr ret = doc.createAttributeNS(ns, attributeName); ret.setTextContent(value); ret.setPrefix(OJBC_NAMESPACE_CONTEXT.getPrefix(ns)); parent.setAttributeNode(ret); return ret; }
From source file:org.talend.designer.maven.utils.PomUtil.java
/** * // w ww . j a v a 2 s . c om * Create pom without refresh eclipse resources * * @param artifact * @return */ public static String generatePom2(MavenArtifact artifact) { try { Project project = ProjectManager.getInstance().getCurrentProject(); IProject fsProject = ResourceUtils.getProject(project); SecureRandom random = new SecureRandom(); IPath tempPath = fsProject.getLocation().append("temp").append("pom" + Math.abs(random.nextLong())); File tmpFolder = new File(tempPath.toPortableString()); tmpFolder.mkdirs(); String pomFile = tempPath.append(TalendMavenConstants.POM_FILE_NAME).toPortableString(); Model pomModel = new Model(); pomModel.setModelVersion(TalendMavenConstants.POM_VERSION); pomModel.setModelEncoding(TalendMavenConstants.DEFAULT_ENCODING); pomModel.setGroupId(artifact.getGroupId()); pomModel.setArtifactId(artifact.getArtifactId()); pomModel.setVersion(artifact.getVersion()); String artifactType = artifact.getType(); if (artifactType == null || "".equals(artifactType)) { artifactType = TalendMavenConstants.PACKAGING_JAR; } pomModel.setPackaging(artifactType); ByteArrayOutputStream buf = new ByteArrayOutputStream(); MavenPlugin.getMaven().writeModel(pomModel, buf); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(false); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); TransformerFactory tfactory = TransformerFactory.newInstance(); Document document = documentBuilder.parse(new ByteArrayInputStream(buf.toByteArray())); Element documentElement = document.getDocumentElement(); NamedNodeMap attributes = documentElement.getAttributes(); if (attributes == null || attributes.getNamedItem("xmlns") == null) { //$NON-NLS-1$ Attr attr = document.createAttribute("xmlns"); //$NON-NLS-1$ attr.setTextContent("http://maven.apache.org/POM/4.0.0"); //$NON-NLS-1$ documentElement.setAttributeNode(attr); } if (attributes == null || attributes.getNamedItem("xmlns:xsi") == null) { //$NON-NLS-1$ Attr attr = document.createAttribute("xmlns:xsi"); //$NON-NLS-1$ attr.setTextContent("http://www.w3.org/2001/XMLSchema-instance"); //$NON-NLS-1$ documentElement.setAttributeNode(attr); } if (attributes == null || attributes.getNamedItem("xsi:schemaLocation") == null) { //$NON-NLS-1$ Attr attr = document.createAttributeNS("http://www.w3.org/2001/XMLSchema-instance", //$NON-NLS-1$ "xsi:schemaLocation"); //$NON-NLS-1$ attr.setTextContent( "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"); //$NON-NLS-1$ documentElement.setAttributeNode(attr); } Transformer transformer = tfactory.newTransformer(); DOMSource source = new DOMSource(document); StreamResult result = new StreamResult(new File(pomFile)); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); //$NON-NLS-1$ transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.transform(source, result); return pomFile; } catch (PersistenceException e) { ExceptionHandler.process(e); } catch (CoreException e) { ExceptionHandler.process(e); } catch (ParserConfigurationException e) { ExceptionHandler.process(e); } catch (SAXException e) { ExceptionHandler.process(e); } catch (IOException e) { ExceptionHandler.process(e); } catch (TransformerConfigurationException e) { ExceptionHandler.process(e); } catch (TransformerException e) { ExceptionHandler.process(e); } return null; }