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); }
Document parseDocument(String filename) throws Exception { FileReader reader = new FileReader(filename); String firstLine = new BufferedReader(reader).readLine(); reader.close(); Document document = null; if (firstLine.startsWith("<?xml")) { System.err.println("XML detected; using default XML parser."); } else { try { Class nekoParserClass = Class.forName("org.cyberneko.html.parsers.DOMParser"); Object parser = nekoParserClass.newInstance(); Method parse = nekoParserClass.getMethod("parse", new Class[] {String.class}); Method getDocument = nekoParserClass.getMethod("getDocument", new Class[0]); parse.invoke(parser, filename); document = (Document) getDocument.invoke(parser); } catch (Exception e) { System.err.println("NekoHTML HTML parser not found; HTML4 support disabled."); } } if (document == null) { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); try { // http://www.w3.org/blog/systeam/2008/02/08/w3c_s_excessive_dtd_traffic factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); } catch (ParserConfigurationException e) { System.err.println("Warning: Could not disable external DTD loading"); } DocumentBuilder builder = factory.newDocumentBuilder(); document = builder.parse(filename); } return document; }
/** * Constructor * * @param filename the XML config file */ public LdapConfig(String filename) throws Exception { DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document document = builder.parse(filename); // -- root element Node node = document.getFirstChild(); while (node != null && node.getNodeType() != Node.ELEMENT_NODE) node = node.getNextSibling(); if (node == null || !node.getNodeName().equals("ldap")) throw new Exception("root element is different from 'ldap'"); this.ldapUrl = node.getAttributes().getNamedItem("url").getNodeValue(); node = node.getFirstChild(); while (node != null) { if (node.getNodeType() == Node.ELEMENT_NODE) { if (node.getNodeName().equals("authentication")) handleAuthentication(node); else if (node.getNodeName().equals("plugins")) handlePlugins(node); else if (node.getNodeName().equals("services")) handleServices(node); else if (node.getNodeName().equals("users")) handleUsers(node); else if (node.getNodeName().equals("groups")) handleGroups(node); else Logging.getLogger().warning("unexepected node : " + node.getNodeName()); } node = node.getNextSibling(); } }
/** * Create from factory a DocumentBuilder and let it create a org.w3c.dom.Document. This method * takes InputSource. After successful finish the document tree is returned. * * @param input a parser input (for URL users use: <code>new InputSource(url.toExternalForm()) * </code> * @param validate if true validating parser is used * @param namespaceAware if true DOM is created by namespace aware parser * @param errorHandler a error handler to notify about exception or <code>null</code> * @param entityResolver SAX entity resolver or <code>null</code>; see class Javadoc for hints * @throws IOException if an I/O problem during parsing occurs * @throws SAXException is thrown if a parser error occurs * @throws FactoryConfigurationError Application developers should never need to directly catch * errors of this type. * @return document representing given input, or null if a parsing error occurs */ public static Document parse( InputSource input, boolean validate, boolean namespaceAware, ErrorHandler errorHandler, EntityResolver entityResolver) throws IOException, SAXException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(validate); factory.setNamespaceAware(namespaceAware); DocumentBuilder builder = null; try { builder = factory.newDocumentBuilder(); } catch (ParserConfigurationException ex) { throw new SAXException( "Cannot create parser satisfying configuration parameters", ex); // NOI18N } if (errorHandler != null) { builder.setErrorHandler(errorHandler); } if (entityResolver != null) { builder.setEntityResolver(entityResolver); } return builder.parse(input); }
/** * 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); } }
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); }
public void saveToXml(String fileName) throws ParserConfigurationException, FileNotFoundException, TransformerException, TransformerConfigurationException { System.out.println("Saving network topology to file " + fileName); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder parser = factory.newDocumentBuilder(); Document doc = parser.newDocument(); Element root = doc.createElement("neuralNetwork"); root.setAttribute("dateOfExport", new Date().toString()); Element layers = doc.createElement("structure"); layers.setAttribute("numberOfLayers", Integer.toString(this.numberOfLayers())); for (int il = 0; il < this.numberOfLayers(); il++) { Element layer = doc.createElement("layer"); layer.setAttribute("index", Integer.toString(il)); layer.setAttribute("numberOfNeurons", Integer.toString(this.getLayer(il).numberOfNeurons())); for (int in = 0; in < this.getLayer(il).numberOfNeurons(); in++) { Element neuron = doc.createElement("neuron"); neuron.setAttribute("index", Integer.toString(in)); neuron.setAttribute( "NumberOfInputs", Integer.toString(this.getLayer(il).getNeuron(in).numberOfInputs())); neuron.setAttribute( "threshold", Double.toString(this.getLayer(il).getNeuron(in).threshold)); for (int ii = 0; ii < this.getLayer(il).getNeuron(in).numberOfInputs(); ii++) { Element input = doc.createElement("input"); input.setAttribute("index", Integer.toString(ii)); input.setAttribute( "weight", Double.toString(this.getLayer(il).getNeuron(in).getInput(ii).weight)); neuron.appendChild(input); } layer.appendChild(neuron); } layers.appendChild(layer); } root.appendChild(layers); doc.appendChild(root); // save File xmlOutputFile = new File(fileName); FileOutputStream fos; Transformer transformer; fos = new FileOutputStream(xmlOutputFile); // Use a Transformer for output TransformerFactory transformerFactory = TransformerFactory.newInstance(); transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(fos); // transform source into result will do save transformer.setOutputProperty("encoding", "iso-8859-2"); transformer.setOutputProperty("indent", "yes"); transformer.transform(source, result); }
/** * Performs an XPATH lookup in an xml document whose filename is specified by the first parameter * (assumed to be in the auxiliary subdirectory) The XPATH expression is supplied as the second * string parameter The return value is of type string e.g. this is currently used primarily for * looking up the Company Prefix Index for encoding a GS1 Company Prefix into a 64-bit EPC tag */ private String xpathlookup(String xml, String expression) { try { // Parse the XML as a W3C document. DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document document = builder.parse(new File(xmldir + File.separator + "auxiliary" + File.separator + xml)); XPath xpath = XPathFactory.newInstance().newXPath(); String rv = (String) xpath.evaluate(expression, document, XPathConstants.STRING); return rv; } catch (ParserConfigurationException e) { System.err.println("ParserConfigurationException caught..."); e.printStackTrace(); return null; } catch (XPathExpressionException e) { System.err.println("XPathExpressionException caught..."); e.printStackTrace(); return null; } catch (SAXException e) { System.err.println("SAXException caught..."); e.printStackTrace(); return null; } catch (IOException e) { System.err.println("IOException caught..."); e.printStackTrace(); return null; } }
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); } } }
// 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 parsePage(String pageCode) { List sections = new ArrayList(); List folders = new ArrayList(); List files = new ArrayList(); int start = pageCode.indexOf("<div id=\"list-view\" class=\"view\""); int end = pageCode.indexOf("<div id=\"gallery-view\" class=\"view\""); String usefulSection = ""; if (start != -1 && end != -1) { usefulSection = pageCode.substring(start, end); } else { debug("Could not parse page"); } try { DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder(); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(usefulSection)); Document doc = db.parse(is); NodeList divs = doc.getElementsByTagName("div"); for (int i = 0; i < divs.getLength(); i++) { Element div = (Element) divs.item(i); boolean isFolder = false; if (div.getAttribute("class").equals("filename")) { NodeList imgs = div.getElementsByTagName("img"); for (int j = 0; j < imgs.getLength(); j++) { Element img = (Element) imgs.item(j); if (img.getAttribute("class").indexOf("folder") > 0) { isFolder = true; } else { isFolder = false; // it's a file } } NodeList anchors = div.getElementsByTagName("a"); Element anchor = (Element) anchors.item(0); String attr = anchor.getAttribute("href"); String fileName = anchor.getAttribute("title"); String fileURL; if (isFolder && !attr.equals("#")) { folders.add(attr); folders.add(fileName); } else if (!isFolder && !attr.equals("#")) { // Dropbox uses ajax to get the file for download, so the url isn't enough. We must be // sneaky here. fileURL = "https://dl.dropbox.com" + attr.substring(23) + "?dl=1"; files.add(fileURL); files.add(fileName); } } } } catch (Exception e) { debug(e.toString()); } sections.add(files); sections.add(folders); return sections; }
/** * Creates an AppConfig using class <code>pAppClass</code> to search for the config file resource. * That class must have a resource file <code>AppConfig.xml</code>. */ private AppConfig(InputSource pInputSource) throws InvalidInputException, DataNotFoundException { try { DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document document = builder.parse(pInputSource); mConfigFileDocument = document; } catch (Exception e) { e.printStackTrace(System.err); throw new InvalidInputException("unable to load XML configuration file", e); } }
public static Document newXMLDocument() { DocumentBuilder dbuilder = null; try { dbuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); } catch (ParserConfigurationException e) { e.printStackTrace(); return null; } return dbuilder.newDocument(); }
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); } } } } } } } } }
/** Возвращает объект Document, который является объектным представлением XML документа. */ private static Document getDocument() throws Exception { try { DocumentBuilderFactory f = DocumentBuilderFactory.newInstance(); f.setValidating(false); DocumentBuilder builder = f.newDocumentBuilder(); return builder.parse(new File("app.xml")); } catch (Exception exception) { String message = "XML parsing error!"; throw new Exception(message); } }
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { try { DateFormat df = DateFormat.getDateTimeInstance(); String titleStr = "C3P0 Status - " + df.format(new Date()); DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance(); DocumentBuilder db = fact.newDocumentBuilder(); Document doc = db.newDocument(); Element htmlElem = doc.createElement("html"); Element headElem = doc.createElement("head"); Element titleElem = doc.createElement("title"); titleElem.appendChild(doc.createTextNode(titleStr)); Element bodyElem = doc.createElement("body"); Element h1Elem = doc.createElement("h1"); h1Elem.appendChild(doc.createTextNode(titleStr)); Element h3Elem = doc.createElement("h3"); h3Elem.appendChild(doc.createTextNode("PooledDataSources")); Element pdsDlElem = doc.createElement("dl"); pdsDlElem.setAttribute("class", "PooledDataSources"); for (Iterator ii = C3P0Registry.getPooledDataSources().iterator(); ii.hasNext(); ) { PooledDataSource pds = (PooledDataSource) ii.next(); StatusReporter sr = findStatusReporter(pds, doc); pdsDlElem.appendChild(sr.reportDtElem()); pdsDlElem.appendChild(sr.reportDdElem()); } headElem.appendChild(titleElem); htmlElem.appendChild(headElem); bodyElem.appendChild(h1Elem); bodyElem.appendChild(h3Elem); bodyElem.appendChild(pdsDlElem); htmlElem.appendChild(bodyElem); res.setContentType("application/xhtml+xml"); TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); Source src = new DOMSource(doc); Result result = new StreamResult(res.getOutputStream()); transformer.transform(src, result); } catch (IOException e) { throw e; } catch (Exception e) { throw new ServletException(e); } }
public static Document getDocument() { Document doc = null; try { DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = dbfac.newDocumentBuilder(); doc = docBuilder.newDocument(); } catch (Exception exc) { log.error("XmlWorks::getDocument()", exc); } return doc; }
public static Document getDocumentE(String filename) throws Exception { File f = new File(filename); if (!f.exists()) { throw new FileNotFoundException(filename); } Document doc = null; DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = dbfac.newDocumentBuilder(); doc = docBuilder.parse(filename); return doc; }
public WikipediaMinerAnnotator(String configFile) throws ParserConfigurationException, FileNotFoundException, SAXException, IOException, XPathExpressionException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(new FileInputStream(configFile)); url = getConfigValue("access", "url", doc); if (url.equals("")) throw new AnnotationException( "Configuration file " + configFile + " has missing value 'url'."); }
public XMLHelper(String root) { this(); try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.newDocument(); setElement((Element) document.appendChild(document.createElement(root))); } catch (ParserConfigurationException e) { // Not quite sure when this would happen severe("Could not extantiate XML builder: " + e.getMessage()); } }
/** * 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(); }
/** @param name creates a node with this name */ public XML(String name) { try { // TODO is there a more efficient way of doing this? wow. DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.newDocument(); node = document.createElement(name); this.parent = null; } catch (ParserConfigurationException pce) { throw new RuntimeException(pce); } }
public apiParser(String sdkfile) { System.out.println(sdkfile); File file = new File(sdkfile); try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(file); NodeList apiList = doc.getElementsByTagName("n1:api"); NodeList inputList = doc.getElementsByTagName("n1:input"); NodeList typeList = doc.getElementsByTagName("n1:type"); for (int i = 0; i < apiList.getLength(); i++) { Node api_node = apiList.item(i); String api_id = api_node.getAttributes().getNamedItem("id").getNodeValue(); String api_name = api_node.getAttributes().getNamedItem("name").getNodeValue(); String input_type_id = inputList.item(i).getAttributes().getNamedItem("type_ref").getNodeValue(); // System.out.println(api_id + " : " + api_name + " : " + input_type_id); ArrayList<String> api_params = new ArrayList<String>(); for (int j = 0; j < typeList.getLength(); j++) { if (input_type_id.equalsIgnoreCase( typeList.item(j).getAttributes().getNamedItem("id").getNodeValue())) { Element e1 = (Element) typeList.item(j); NodeList param_l = e1.getElementsByTagName("n1:param"); for (int k = 0; k < param_l.getLength(); k++) { String param_name = param_l.item(k).getAttributes().getNamedItem("name").getNodeValue(); // String param_desc = // param_l.item(k).getAttributes().getNamedItem("desc").getNodeValue(); api_params.add(param_name); // System.out.println(param_name +":"+param_desc); } break; } } apiRoom s_room = new apiRoom(api_id, api_name, api_params); apiRooms.add(s_room); } } catch (Exception e) { e.printStackTrace(); } }
public static void main(String[] args) { try { DocumentBuilderFactory dBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dBuilderFactory.newDocumentBuilder(); Document document = dBuilder.parse("DOMSample.xml"); Element rootElement = document.getDocumentElement(); System.out.println("Root Element's Value : " + rootElement.getTextContent()); } catch (Exception e) { e.printStackTrace(System.err); } }
public static void main(String[] args) { try { // Find the implementation DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder builder = factory.newDocumentBuilder(); DOMImplementation impl = builder.getDOMImplementation(); // Create the document DocumentType svgDOCTYPE = impl.createDocumentType( "svg", "-//W3C//DTD SVG 1.0//EN", "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd"); Document doc = impl.createDocument("http://www.w3.org/2000/svg", "svg", svgDOCTYPE); // Fill the document Node rootElement = doc.getDocumentElement(); ProcessingInstruction xmlstylesheet = doc.createProcessingInstruction( "xml-stylesheet", "type=\"text/css\" href=\"standard.css\""); Comment comment = doc.createComment("An example from Chapter 10 of Processing XML with Java"); doc.insertBefore(comment, rootElement); doc.insertBefore(xmlstylesheet, rootElement); Node desc = doc.createElementNS("http://www.w3.org/2000/svg", "desc"); rootElement.appendChild(desc); Text descText = doc.createTextNode("An example from Processing XML with Java"); desc.appendChild(descText); // Serialize the document onto System.out TransformerFactory xformFactory = TransformerFactory.newInstance(); Transformer idTransform = xformFactory.newTransformer(); Source input = new DOMSource(doc); Result output = new StreamResult(System.out); idTransform.transform(input, output); } catch (FactoryConfigurationError e) { System.out.println("Could not locate a JAXP factory class"); } catch (ParserConfigurationException e) { System.out.println("Could not locate a JAXP DocumentBuilder class"); } catch (DOMException e) { System.err.println(e); } catch (TransformerConfigurationException e) { System.err.println(e); } catch (TransformerException e) { System.err.println(e); } }
public static void main(String args[]) { try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); factory.setValidating(true); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(args[0]); } catch (SAXException e) { // e.printStackTrace(); System.out.println(e.getMessage()); } catch (Exception e) { // e.printStackTrace(); } }
public static final Skeleton loadSkeleton(File file) { try { FileInputStream input_stream = new FileInputStream(file); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(true); DocumentBuilder builder = factory.newDocumentBuilder(); builder.setErrorHandler(new GeometryErrorHandler()); Document document = builder.parse(input_stream); Element root = document.getDocumentElement(); return parseSkeleton(root); } catch (Exception e) { throw new RuntimeException(e); } }
/** * Method responsible for creating Document type response * * @param responseObject * @return Document or Null if exception occurs */ protected Document createResponseObject(Map<String, String> responseObject) throws ResponseException { try { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); // root elements Document doc = docBuilder.newDocument(); Element rootElement = doc.createElement("snmp-response-message"); doc.appendChild(rootElement); Element status = doc.createElement("status"); rootElement.appendChild(status); Element result = doc.createElement("result"); result.appendChild(doc.createTextNode(String.valueOf(resultCode))); status.appendChild(result); Element description = doc.createElement("description"); description.appendChild(doc.createTextNode(descriptionText)); status.appendChild(description); Element operation = doc.createElement("weatherProbe"); rootElement.appendChild(operation); Attr attr = doc.createAttribute("ip"); attr.setValue(att.get("IP-ADDRESS")); operation.setAttributeNode(attr); if (resultCode != 0) { return doc; } for (Map.Entry<String, String> entry : responseObject.entrySet()) { Element nextElement = doc.createElement(entry.getKey()); nextElement.appendChild(doc.createTextNode(entry.getValue())); operation.appendChild(nextElement); } return doc; } catch (ParserConfigurationException e) { LOG.error(e.toString()); throw new ResponseException( "<snmp-response-message><status><result>2</result><description>" + e.toString() + "</description></status><weatherProbe ip=\"" + att.get("IP-ADDRESS") + "\"/></snmp-response-message>"); } }
static { try { URL url = SpellCheckActivator.bundleContext.getBundle().getResource(RESOURCE_LOC); InputStream stream = url.openStream(); if (stream == null) throw new IOException(); // strict parsing options DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(false); factory.setIgnoringComments(true); factory.setIgnoringElementContentWhitespace(true); // parses configuration xml /*- * Warning: Felix is unable to import the com.sun.rowset.internal * package, meaning this can't use the XmlErrorHandler. This causes * a warning and a default handler to be attached. Otherwise this * should have: builder.setErrorHandler(new XmlErrorHandler()); */ DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(stream); // iterates over nodes, parsing contents Node root = doc.getChildNodes().item(1); NodeList categories = root.getChildNodes(); for (int i = 0; i < categories.getLength(); ++i) { Node node = categories.item(i); if (node.getNodeName().equals(NODE_DEFAULTS)) { parseDefaults(node.getChildNodes()); } else if (node.getNodeName().equals(NODE_LOCALES)) { parseLocales(node.getChildNodes()); } else { logger.warn("Unrecognized category: " + node.getNodeName()); } } } catch (IOException exc) { logger.error("Unable to load spell checker parameters", exc); } catch (SAXException exc) { logger.error("Unable to parse spell checker parameters", exc); } catch (ParserConfigurationException exc) { logger.error("Unable to parse spell checker parameters", exc); } }
/** * Given a DICOM object encoded as a list of attributes, get an XML document as a DOM tree. * * @param list the list of DICOM attributes */ public Document getDocument(AttributeList list) { Document document = db.newDocument(); org.w3c.dom.Node element = document.createElement("DicomObject"); document.appendChild(element); addAttributesFromListToNode(list, document, element); return document; }