/** * Process index terms. * * @param theInput input document * @return read index terms * @throws ProcessException if processing index terms failed */ public IndexPreprocessResult process(final Document theInput) throws ProcessException { final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = null; try { documentBuilder = documentBuilderFactory.newDocumentBuilder(); } catch (final ParserConfigurationException e) { throw new RuntimeException("Unable to create a document builder: " + e.getMessage(), e); } final Document doc = documentBuilder.newDocument(); final Node rootElement = theInput.getDocumentElement(); final ArrayList<IndexEntry> indexes = new ArrayList<IndexEntry>(); final IndexEntryFoundListener listener = new IndexEntryFoundListener() { public void foundEntry(final IndexEntry theEntry) { indexes.add(theEntry); } }; final Node node = processCurrNode(rootElement, doc, listener)[0]; doc.appendChild(node); doc.getDocumentElement().setAttribute(XMLNS_ATTRIBUTE + ":" + this.prefix, this.namespace_url); return new IndexPreprocessResult(doc, (IndexEntry[]) indexes.toArray(new IndexEntry[0])); }
private static UpgradeStringResult transformXml( String xml, String newFormatVersion, UpgradeOp... ops) { try { DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder; builder = builderFactory.newDocumentBuilder(); Document document = builder.parse(new InputSource(new StringReader(xml))); // Check that this is a NodeBox document and set the new formatVersion. Element root = document.getDocumentElement(); checkArgument(root.getTagName().equals("ndbx"), "This is not a valid NodeBox document."); root.setAttribute("formatVersion", newFormatVersion); // Loop through all upgrade operations. ArrayList<String> warnings = new ArrayList<String>(); for (UpgradeOp op : ops) { op.start(root); transformXmlRecursive(document.getDocumentElement(), op); op.end(root); warnings.addAll(op.getWarnings()); } TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(document); StringWriter sw = new StringWriter(); StreamResult result = new StreamResult(sw); transformer.transform(source, result); return new UpgradeStringResult(sw.toString(), warnings); } catch (Exception e) { throw new RuntimeException("Error while upgrading to " + newFormatVersion + ".", e); } }
/** * Appends WMS tiled image layer configuration elements to the superclass configuration document. * * @param params configuration parameters describing this WMS tiled image layer. * @return a WMS tiled image layer configuration document. */ protected Document createConfigurationDocument(AVList params) { Document doc = super.createConfigurationDocument(params); if (doc == null || doc.getDocumentElement() == null) return doc; LayerConfiguration.createWMSTiledImageLayerElements(params, doc.getDocumentElement()); return doc; }
public static String documentToString(Document document, boolean standalone) throws Exception { String prol = "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"" + (standalone ? "yes" : "no") + "\"?>"; return prol + nodeToString( document.getDocumentElement(), new HashSet<String>(), document.getDocumentElement().getNamespaceURI()); }
/** * Set a property of a resource to a value. * * @param name the property name * @param value the property value * @exception com.ibm.webdav.WebDAVException */ public void setProperty(String name, Element value) throws WebDAVException { // load the properties Document propertiesDocument = resource.loadProperties(); Element properties = propertiesDocument.getDocumentElement(); String ns = value.getNamespaceURI(); Element property = null; if (ns == null) { property = (Element) ((Element) properties).getElementsByTagName(value.getTagName()).item(0); } else { property = (Element) properties.getElementsByTagNameNS(ns, value.getLocalName()).item(0); } if (property != null) { try { properties.removeChild(property); } catch (DOMException exc) { } } properties.appendChild(propertiesDocument.importNode(value, true)); // write out the properties resource.saveProperties(propertiesDocument); }
private void guardaRes(String resu, CliGol cliGol) throws ParserConfigurationException, SAXException, IOException { String[] nodos = {"NoHit", "Hit", "Buro"}; DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder(); InputSource is = new InputSource(new StringReader(resu)); Document xml = db.parse(is); Element raiz = xml.getDocumentElement(); String nombre = obtenerNombre(raiz); for (String s : nodos) { Node nodo = raiz.getElementsByTagName(s) == null ? null : raiz.getElementsByTagName(s).item(0); if (nodo != null) { String informacion = sustraerInformacionNodo(cliGol, nodo); guardarEnListas(nodo.getNodeName(), nombre + "," + informacion); } } }
/** * Parses a given .svg for nodes * * @return <b>bothNodeLists</b> an Array with two NodeLists */ public static NodeList[] parseSVG(Date date) { /* As it has to return two things, it can not return them * directly but has to encapsulate it in another object. */ NodeList[] bothNodeLists = new NodeList[2]; ; try { DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); String SVGFileName = "./draw_map_svg.svg"; File svgMap = new File(SVGFileName); System.out.println("Parsing the svg"); // Status message #1 Parsing System.out.println("This should not longer than 30 seconds"); // Status message #2 Parsing Document doc = docBuilder.parse(SVGFileName); // "text" is the actual planet/warplanet NodeList listOfPlanetsAsXMLNode = doc.getElementsByTagName("text"); // "line" is the line drawn by a warplanet. Used for calculation of warplanet coordinates. NodeList listOfLinesAsXMLNode = doc.getElementsByTagName("line"); bothNodeLists[0] = listOfPlanetsAsXMLNode; bothNodeLists[1] = listOfLinesAsXMLNode; // normalize text representation doc.getDocumentElement().normalize(); // Build the fileName the .svg should be renamed to, using the dateStringBuilder String newSVGFileName = MapTool.dateStringBuilder(MapTool.getKosmorDate(date), date); newSVGFileName = newSVGFileName.concat(" - Map - kosmor.com - .svg"); // Making sure the directory does exist, if not, it is created File svgdir = new File("svg"); if (!svgdir.exists() || !svgdir.isDirectory()) { svgdir.mkdir(); } svgMap.renameTo(new File(svgdir + "\\" + newSVGFileName)); System.out.println("Done parsing"); // Status message #3 Parsing } catch (SAXParseException err) { System.out.println( "** Parsing error" + ", line " + err.getLineNumber() + ", uri " + err.getSystemId()); System.out.println(" " + err.getMessage()); } catch (SAXException e) { Exception x = e.getException(); ((x == null) ? e : x).printStackTrace(); } catch (Throwable t) { t.printStackTrace(); } return bothNodeLists; }
/* PRIVATE METHODS */ private DOMDocument createDomDocument(String rootName) { DOMDocument domDocument = new DOMDocument(nsURI, rootName, null); Document document = domDocument.getDocument(); Element root = document.getDocumentElement(); if (includeTypeInfo) { root.setAttributeNS( XMLConstants.XMLNS_ATTRIBUTE_NS_URI, XMLConstants.XMLNS_ATTRIBUTE + ":" + nsPrefix, nsURI); root.setAttributeNS( XMLConstants.XMLNS_ATTRIBUTE_NS_URI, XMLConstants.XMLNS_ATTRIBUTE + ":" + NamespaceConstants.NSPREFIX_SCHEMA_XSD, NamespaceConstants.NSURI_SCHEMA_XSD); root.setAttributeNS( XMLConstants.XMLNS_ATTRIBUTE_NS_URI, XMLConstants.XMLNS_ATTRIBUTE + ":" + NamespaceConstants.NSPREFIX_SCHEMA_XSI, NamespaceConstants.NSURI_SCHEMA_XSI); root.setAttributeNS( XMLConstants.XMLNS_ATTRIBUTE_NS_URI, XMLConstants.XMLNS_ATTRIBUTE + ":" + NamespaceConstants.NSPREFIX_SOAP_ENCODING, NamespaceConstants.NSURI_SOAP_ENCODING); root.setAttributeNS( XMLConstants.XMLNS_ATTRIBUTE_NS_URI, XMLConstants.XMLNS_ATTRIBUTE + ":" + Constants.NS_PREFIX_XMLSOAP, Constants.NS_URI_XMLSOAP); } return domDocument; }
/** * WhiteboardObjectTextJabberImpl constructor. * * @param xml the XML string object to parse. */ public WhiteboardObjectTextJabberImpl(String xml) { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder; try { builder = factory.newDocumentBuilder(); InputStream in = new ByteArrayInputStream(xml.getBytes()); Document doc = builder.parse(in); Element e = doc.getDocumentElement(); String elementName = e.getNodeName(); if (elementName.equals("text")) { // we have a text String id = e.getAttribute("id"); double x = Double.parseDouble(e.getAttribute("x")); double y = Double.parseDouble(e.getAttribute("y")); String fill = e.getAttribute("fill"); String fontFamily = e.getAttribute("font-family"); int fontSize = Integer.parseInt(e.getAttribute("font-size")); String text = e.getTextContent(); this.setID(id); this.setWhiteboardPoint(new WhiteboardPoint(x, y)); this.setFontName(fontFamily); this.setFontSize(fontSize); this.setText(text); this.setColor(Color.decode(fill).getRGB()); } } catch (ParserConfigurationException ex) { if (logger.isDebugEnabled()) logger.debug("Problem WhiteboardObject : " + xml); } catch (IOException ex) { if (logger.isDebugEnabled()) logger.debug("Problem WhiteboardObject : " + xml); } catch (Exception ex) { if (logger.isDebugEnabled()) logger.debug("Problem WhiteboardObject : " + xml); } }
// Serialize the bean using the specified namespace prefix & uri public String serialize(Object bean) throws IntrospectionException, IllegalAccessException { // Use the class name as the name of the root element String className = bean.getClass().getName(); String rootElementName = null; if (bean.getClass().isAnnotationPresent(ObjectXmlAlias.class)) { AnnotatedElement annotatedElement = bean.getClass(); ObjectXmlAlias aliasAnnotation = annotatedElement.getAnnotation(ObjectXmlAlias.class); rootElementName = aliasAnnotation.value(); } // Use the package name as the namespace URI Package pkg = bean.getClass().getPackage(); nsURI = pkg.getName(); // Remove a trailing semi-colon (;) if present (i.e. if the bean is an array) className = StringUtils.deleteTrailingChar(className, ';'); StringBuffer sb = new StringBuffer(className); String objectName = sb.delete(0, sb.lastIndexOf(".") + 1).toString(); domDocument = createDomDocument(objectName); document = domDocument.getDocument(); Element root = document.getDocumentElement(); // Parse the bean elements getBeanElements(root, rootElementName, className, bean); StringBuffer xml = new StringBuffer(); if (prettyPrint) xml.append(domDocument.serialize(lineSeperator, indentChars, includeXmlProlog)); else xml.append(domDocument.serialize(includeXmlProlog)); if (!includeTypeInfo) { int index = xml.indexOf(root.getNodeName()); xml.delete(index - 1, index + root.getNodeName().length() + 2); xml.delete(xml.length() - root.getNodeName().length() - 4, xml.length()); } return xml.toString(); }
public ArrayList<String> parseXML() throws Exception { ArrayList<String> ret = new ArrayList<String>(); handshake(); URL url = new URL( "http://mangaonweb.com/page.do?cdn=" + cdn + "&cpn=book.xml&crcod=" + crcod + "&rid=" + (int) (Math.random() * 10000)); String page = DownloaderUtils.getPage(url.toString(), "UTF-8", cookies); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); InputSource is = new InputSource(new StringReader(page)); Document d = builder.parse(is); Element doc = d.getDocumentElement(); NodeList pages = doc.getElementsByTagName("page"); total = pages.getLength(); for (int i = 0; i < pages.getLength(); i++) { Element e = (Element) pages.item(i); ret.add(e.getAttribute("path")); } return (ret); }
// Lee la configuracion que se encuentra en conf/RegistryConf private void readConfXml() { try { File inputFile = new File("src/java/Conf/RegistryConf.xml"); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(inputFile); doc.getDocumentElement().normalize(); NodeList nList = doc.getElementsByTagName("RegistryConf"); for (int i = 0; i < nList.getLength(); i++) { Node nNode = nList.item(i); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; RegistryConf reg = new RegistryConf(); String aux; int idSensor; int value; aux = eElement.getElementsByTagName("idSensor").item(0).getTextContent(); idSensor = Integer.parseInt(aux); reg.setIdSensor(idSensor); aux = eElement.getElementsByTagName("saveType").item(0).getTextContent(); reg.setSaveTypeString(aux); aux = eElement.getElementsByTagName("value").item(0).getTextContent(); value = Integer.parseInt(aux); reg.setValue(value); registryConf.add(reg); lastRead.put(idSensor, 0); } } } catch (Exception e) { e.printStackTrace(); } }
public List<Customer> unmarshallCustomers(String fileStringPathname) { List<Customer> customerList = new ArrayList<Customer>(); File docFile = new File(fileStringPathname); Document document = null; try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); dbf.setValidating(true); dbf.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "customers.xsd"); DocumentBuilder documentBuilder = dbf.newDocumentBuilder(); document = documentBuilder.parse(docFile); } catch (Exception e) { System.out.println( e .getMessage()); // To change body of catch statement use File | Settings | File // Templates. } Element root = document.getDocumentElement(); NodeList children = root.getChildNodes(); Node node; for (int i = 0; i < children.getLength(); i++) { node = children.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { customerList.add(customerUnmarshaller(node)); } } return customerList; }
public Document toDOM(Serializable structure) { ContextFreePumpingLemma pl = (ContextFreePumpingLemma) structure; Document doc = newEmptyDocument(); Element elem = doc.getDocumentElement(); elem.appendChild(createElement(doc, LEMMA_NAME, null, pl.getTitle())); elem.appendChild(createElement(doc, FIRST_PLAYER, null, pl.getFirstPlayer())); elem.appendChild(createElement(doc, M_NAME, null, "" + pl.getM())); elem.appendChild(createElement(doc, W_NAME, null, "" + pl.getW())); elem.appendChild(createElement(doc, I_NAME, null, "" + pl.getI())); elem.appendChild(createElement(doc, U_NAME, null, "" + pl.getU().length())); elem.appendChild(createElement(doc, V_NAME, null, "" + pl.getV().length())); elem.appendChild(createElement(doc, X_NAME, null, "" + pl.getX().length())); elem.appendChild(createElement(doc, Y_NAME, null, "" + pl.getY().length())); // Encode the list of attempts. ArrayList attempts = pl.getAttempts(); if (attempts != null && attempts.size() > 0) for (int i = 0; i < attempts.size(); i++) elem.appendChild(createElement(doc, ATTEMPT, null, (String) attempts.get(i))); // Encode the list of attempts. ArrayList cases = pl.getDoneCases(); if (cases != null && cases.size() > 0) for (int i = 0; i < cases.size(); i++) elem.appendChild(createCaseElement(doc, (Case) cases.get(i))); return doc; }
public static void main(String args[]) throws Exception { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder parser = dbf.newDocumentBuilder(); Document xmldoc = parser.parse("addr.xml"); Element root = xmldoc.getDocumentElement(); System.out.println(root); }
public static void testEnum() throws Exception { Builder b = new Builder(); b.addClasspath(new File("bin")); b.setProperty("Export-Package", "test.metatype"); b.setProperty("-metatype", "*"); b.build(); assertEquals(0, b.getErrors().size()); assertEquals(0, b.getWarnings().size()); Resource r = b.getJar().getResource("OSGI-INF/metatype/test.metatype.MetatypeTest$Enums.xml"); IO.copy(r.openInputStream(), System.err); Document d = db.parse(r.openInputStream()); assertEquals( "http://www.osgi.org/xmlns/metatype/v1.1.0", d.getDocumentElement().getNamespaceURI()); Properties p = new Properties(); p.setProperty("r", "requireConfiguration"); p.setProperty("i", "ignoreConfiguration"); p.setProperty("o", "optionalConfiguration"); Enums enums = Configurable.createConfigurable(Enums.class, (Map<Object, Object>) p); assertEquals(Enums.X.requireConfiguration, enums.r()); assertEquals(Enums.X.ignoreConfiguration, enums.i()); assertEquals(Enums.X.optionalConfiguration, enums.o()); }
/** @param eNewParent */ public static void debugOutput(Element eNewParent) { try { Document d = XML.newDocument("test"); d.getDocumentElement().appendChild(d.importNode(eNewParent, true)); System.err.println(XML.saveString(d).replaceAll("(^(.|[\\n\\r])*<test>)|(</test>$)", "")); } catch (Exception e) { } }
/** * Given a DICOM object encoded as an XML document convert it to a list of attributes. * * @param document the XML document * @return the list of DICOM attributes * @exception DicomException */ public AttributeList getAttributeList(Document document) throws DicomException { AttributeList list = new AttributeList(); org.w3c.dom.Node element = document.getDocumentElement(); // should be DicomObject addAttributesFromNodeToList(list, element); // System.err.println("XMLRepresentationOfDicomObjectFactory.getAttributeList(Document // document): List is "+list); return list; }
/** * @param sourceFile File to read from * @return List of String objects with the shas */ public static FileRequestFileContent readRequestFile(final File sourceFile) { if (!sourceFile.isFile() || !(sourceFile.length() > 0)) { return null; } Document d = null; try { d = XMLTools.parseXmlFile(sourceFile.getPath()); } catch (final Throwable t) { logger.log(Level.SEVERE, "Exception in readRequestFile, during XML parsing", t); return null; } if (d == null) { logger.log(Level.SEVERE, "Could'nt parse the request file"); return null; } final Element rootNode = d.getDocumentElement(); if (rootNode.getTagName().equals(TAG_FrostFileRequestFile) == false) { logger.severe( "Error: xml request file does not contain the root tag '" + TAG_FrostFileRequestFile + "'"); return null; } final String timeStampStr = XMLTools.getChildElementsTextValue(rootNode, TAG_timestamp); if (timeStampStr == null) { logger.severe("Error: xml file does not contain the tag '" + TAG_timestamp + "'"); return null; } final long timestamp = Long.parseLong(timeStampStr); final List<Element> nodelist = XMLTools.getChildElementsByTagName(rootNode, TAG_shaList); if (nodelist.size() != 1) { logger.severe("Error: xml request files must contain only one element '" + TAG_shaList + "'"); return null; } final Element rootShaNode = nodelist.get(0); final List<String> shaList = new LinkedList<String>(); final List<Element> xmlKeys = XMLTools.getChildElementsByTagName(rootShaNode, TAG_sha); for (final Element el : xmlKeys) { final Text txtname = (Text) el.getFirstChild(); if (txtname == null) { continue; } final String sha = txtname.getData(); shaList.add(sha); } final FileRequestFileContent content = new FileRequestFileContent(timestamp, shaList); return content; }
public WarXMLReader(String fileName, War w) throws ParserConfigurationException, SAXException, IOException { this.war = w; factory = DocumentBuilderFactory.newInstance(); builder = factory.newDocumentBuilder(); document = builder.parse(new File(fileName)); root = document.getDocumentElement(); }
/** * ** Gets a virtual DBRecord from the specified remote service ** @param servReq The remote web * service ** @return The virtual DBRecord (cannot be saved or reloaded) */ @SuppressWarnings("unchecked") public gDBR getVirtualDBRecord(final ServiceRequest servReq) throws DBException { String CMD_dbget = DBFactory.CMD_dbget; String TAG_Response = servReq.getTagResponse(); String TAG_Record = DBFactory.TAG_Record; String ATTR_command = servReq.getAttrCommand(); String ATTR_result = servReq.getAttrResult(); /* send request / get response */ Document xmlDoc = null; try { xmlDoc = servReq.sendRequest( CMD_dbget, new ServiceRequest.RequestBody() { public StringBuffer appendRequestBody(StringBuffer sb, int indent) { return DBRecordKey.this.toRequestXML(sb, indent); } }); } catch (IOException ioe) { Print.logException("Error", ioe); throw new DBException("Request read error", ioe); } /* parse 'GTSResponse' */ Element gtsResponse = xmlDoc.getDocumentElement(); if (!gtsResponse.getTagName().equalsIgnoreCase(TAG_Response)) { Print.logError("Request XML does not start with '%s'", TAG_Response); throw new DBException("Response XML does not begin eith '" + TAG_Response + "'"); } /* request command/argument */ String cmd = StringTools.trim(gtsResponse.getAttribute(ATTR_command)); String result = StringTools.trim(gtsResponse.getAttribute(ATTR_result)); if (StringTools.isBlank(result)) { result = StringTools.trim(gtsResponse.getAttribute("type")); } if (!result.equalsIgnoreCase("success")) { Print.logError("Response indicates failure"); throw new DBException("Response does not indicate 'success'"); } /* Record */ NodeList rcdList = XMLTools.getChildElements(gtsResponse, TAG_Record); if (rcdList.getLength() <= 0) { Print.logError("No 'Record' tags"); throw new DBException("GTSResponse does not contain any 'Record' tags"); } Element rcdElem = (Element) rcdList.item(0); /* return DBRecord */ gDBR dbr = (gDBR) DBFactory.parseXML_DBRecord(rcdElem); dbr.setVirtual(true); return dbr; }
private void loadFromXml(String fileName) throws ParserConfigurationException, SAXException, IOException, ParseException { System.out.println("NeuralNetwork : loading network topology from file " + fileName); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder parser = factory.newDocumentBuilder(); Document doc = parser.parse(fileName); Node nodeNeuralNetwork = doc.getDocumentElement(); if (!nodeNeuralNetwork.getNodeName().equals("neuralNetwork")) throw new ParseException( "[Error] NN-Load: Parse error in XML file, neural network couldn't be loaded.", 0); // nodeNeuralNetwork ok // indexNeuralNetworkContent -> indexStructureContent -> indexLayerContent -> indexNeuronContent // -> indexNeuralInputContent NodeList nodeNeuralNetworkContent = nodeNeuralNetwork.getChildNodes(); for (int innc = 0; innc < nodeNeuralNetworkContent.getLength(); innc++) { Node nodeStructure = nodeNeuralNetworkContent.item(innc); if (nodeStructure.getNodeName().equals("structure")) { // for structure element NodeList nodeStructureContent = nodeStructure.getChildNodes(); for (int isc = 0; isc < nodeStructureContent.getLength(); isc++) { Node nodeLayer = nodeStructureContent.item(isc); if (nodeLayer.getNodeName().equals("layer")) { // for layer element NeuralLayer neuralLayer = new NeuralLayer(this); this.listLayers.add(neuralLayer); NodeList nodeLayerContent = nodeLayer.getChildNodes(); for (int ilc = 0; ilc < nodeLayerContent.getLength(); ilc++) { Node nodeNeuron = nodeLayerContent.item(ilc); if (nodeNeuron.getNodeName().equals("neuron")) { // for neuron in layer Neuron neuron = new Neuron( Double.parseDouble(((Element) nodeNeuron).getAttribute("threshold")), neuralLayer); neuralLayer.listNeurons.add(neuron); NodeList nodeNeuronContent = nodeNeuron.getChildNodes(); for (int inc = 0; inc < nodeNeuronContent.getLength(); inc++) { Node nodeNeuralInput = nodeNeuronContent.item(inc); // if (nodeNeuralInput==null) System.out.print("-"); else System.out.print("*"); if (nodeNeuralInput.getNodeName().equals("input")) { // System.out.println("neuron at // STR:"+innc+" LAY:"+isc+" NEU:"+ilc+" INP:"+inc); NeuralInput neuralInput = new NeuralInput( Double.parseDouble(((Element) nodeNeuralInput).getAttribute("weight")), neuron); neuron.listInputs.add(neuralInput); } } } } } } } } }
public void getClassName() { try { DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); Document doc = docBuilder.parse(new File("src/resources/classdata.xml")); doc.getDocumentElement().normalize(); NodeList listOfClasses = doc.getElementsByTagName("class"); classes = new String[listOfClasses.getLength()]; amountClasses = listOfClasses.getLength(); String classID; String className; int classIDint; for (int s = 0; s < listOfClasses.getLength(); s++) { Node firstPersonNode = listOfClasses.item(s); if (firstPersonNode.getNodeType() == Node.ELEMENT_NODE) { Element firstClassElement = (Element) firstPersonNode; NodeList idList = firstClassElement.getElementsByTagName("id"); Element idElement = (Element) idList.item(0); NodeList textLNList = idElement.getChildNodes(); classID = ((Node) textLNList.item(0)).getNodeValue().trim(); NodeList NameList = firstClassElement.getElementsByTagName("name"); Element NameElement = (Element) NameList.item(0); NodeList textFNList = NameElement.getChildNodes(); className = ((Node) textFNList.item(0)).getNodeValue().trim(); classIDint = Integer.parseInt(classID); classes[classIDint] = className; } // end of if clause } // end of for loop with s var } catch (SAXParseException err) { System.out.println( "** Parsing error" + ", line " + err.getLineNumber() + ", uri " + err.getSystemId()); System.out.println(" " + err.getMessage()); } catch (SAXException e) { Exception x = e.getException(); ((x == null) ? e : x).printStackTrace(); } catch (Throwable t) { t.printStackTrace(); } // System.exit (0); }
private static Element readXmlFile(GenericFile file) { try { BufferedReader reader = new BufferedReader(file.getReader()); StringBuilder sBuilder = new StringBuilder(); for (String line = reader.readLine(); line != null; line = reader.readLine()) { sBuilder.append(line); sBuilder.append("\n"); } DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(new ByteArrayInputStream(sBuilder.toString().getBytes())); doc.getDocumentElement().normalize(); return doc.getDocumentElement(); } catch (Exception e) { e.printStackTrace(); System.err.println(e.getMessage()); return null; } }
public XsdDOMValidator(Document document) throws SAXException { AssertArgument.isNotNull(document, "document"); this.document = document; // Get the default namespace... String defaultNamespaceString = getDefaultNamespace(document.getDocumentElement()); if (defaultNamespaceString != null) { try { defaultNamespace = new URI(defaultNamespaceString); } catch (URISyntaxException e) { throw new SAXException( "Cannot validate this document with this class. Namespaces must be valid URIs. Default Namespace: '" + defaultNamespaceString + "'.", e); } } // Get the full namespace list... gatherNamespaces(document.getDocumentElement(), namespaces); }
/** * return the DOM root of the specified XML file * * @param xmlFile * @return */ public static Element getXMLroot(String xmlFile) { try { DOMParser p = new DOMParser(); p.parse(xmlFile); Document doc = p.getDocument(); return doc.getDocumentElement(); } catch (Exception e) { e.getStackTrace(); logger.fatal(e.getMessage()); } return null; }
/** * Constructs an overview-node in the pre-html where all steps are described. Also, information * about valid and non-valid form-schema's are placed in the steps-overview. * * <p>The node looks like this: * * <pre> * <steps-validator valid="false" allowsave="false" allowcancel="true"> * <step form-schema="schema-id" valid="true" /> * <step form-schema="schema-id" valid="false" /> * </steps-validator> * </pre> * * THis method creates a steps-overview which can be used by the html to show what forms are valid * and what are not. * * @param prehtml the prehtml data node * @param schema the original wizardschema */ public static void createStepsOverview(Document prehtml, Document schema) { // remove a "steps-validator" node if it exists. Node overview = Utils.selectSingleNode(prehtml, "/*/steps-overview"); if (overview != null) prehtml.getDocumentElement().removeChild(overview); // create new overview node overview = prehtml.createElement("steps-validator"); Utils.setAttribute(overview, "allowcancel", "true"); int invalidforms = 0; // iterate through all defined steps NodeList steps = Utils.selectNodeList(schema, "/*/steps/step"); for (int i = 0; i < steps.getLength(); i++) { Node step = steps.item(i); String schemaid = Utils.getAttribute(step, "form-schema", ""); if (!schemaid.equals("")) { // find the referred form and check if the form is valid. Node form = Utils.selectSingleNode(prehtml, "/*/form[@id='" + schemaid + "']"); if (form != null) { Node validationerror = Utils.selectSingleNode(form, ".//field/validator[@valid='false']"); boolean valid = (validationerror == null); // copy step information to overview node and store validation results. Node newstep = prehtml.importNode(step.cloneNode(true), true); overview.appendChild(newstep); Utils.setAttribute(newstep, "valid", valid + ""); if (!valid) invalidforms++; } } } // store global information about validationresults Utils.setAttribute(overview, "allowsave", (invalidforms == 0) + ""); Utils.setAttribute(overview, "valid", (invalidforms == 0) + ""); // store new overview node in the prehtml. prehtml.getDocumentElement().appendChild(overview); }
/** * Advanced users only; use loadXML() in PApplet. * * <p>Added extra code to handle \u2028 (Unicode NLF), which is sometimes inserted by web browsers * (Safari?) and not distinguishable from a "real" LF (or CRLF) in some text editors (i.e. * TextEdit on OS X). Only doing this for XML (and not all Reader objects) because LFs are * essential. https://github.com/processing/processing/issues/2100 * * @nowebref */ public XML(final Reader reader, String options) throws IOException, ParserConfigurationException, SAXException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // Prevent 503 errors from www.w3.org try { factory.setAttribute("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); } catch (IllegalArgumentException e) { // ignore this; Android doesn't like it } // without a validating DTD, this doesn't do anything since it doesn't know what is ignorable // factory.setIgnoringElementContentWhitespace(true); factory.setExpandEntityReferences(false); // factory.setExpandEntityReferences(true); // factory.setCoalescing(true); // builderFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); DocumentBuilder builder = factory.newDocumentBuilder(); // builder.setEntityResolver() // SAXParserFactory spf = SAXParserFactory.newInstance(); // spf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); // SAXParser p = spf.newSAXParser(); // builder = DocumentBuilderFactory.newDocumentBuilder(); // builder = new SAXBuilder(); // builder.setValidation(validating); Document document = builder.parse( new InputSource( new Reader() { @Override public int read(char[] cbuf, int off, int len) throws IOException { int count = reader.read(cbuf, off, len); for (int i = 0; i < count; i++) { if (cbuf[off + i] == '\u2028') { cbuf[off + i] = '\n'; } } return count; } @Override public void close() throws IOException { reader.close(); } })); node = document.getDocumentElement(); }
public void load(InputStream is) throws IOException, ParserConfigurationException, SAXException { doc = db.parse(is); docElt = doc.getDocumentElement(); if (docElt.getTagName().equals(docElementName)) { NodeList nl = docElt.getElementsByTagName(trackElementName); for (int i = 0; i < nl.getLength(); i++) { Element elt = (Element) nl.item(i); Track track = new Track(elt); tracks.add(track); hash.put(track.getKey(), track); } } }
public void loadXML(String fname) { try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder db = dbf.newDocumentBuilder(); File f = new File(fname); Document d = db.parse(f); Element e = d.getDocumentElement(); parseChildren(e); } catch (Exception e) { e.printStackTrace(); } }