/**
   * 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);
    }
  }
 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;
 }
예제 #3
0
  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);
  }
예제 #4
0
  // 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();
    }
  }
예제 #5
0
  /**
   * 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);
  }
예제 #6
0
 public static Document readXMLData(String dataXML) throws Exception {
   if (dataXML == null) return null;
   ByteArrayInputStream xmlSrcStream = new ByteArrayInputStream(dataXML.getBytes());
   DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
   dbf.setValidating(false);
   return dbf.newDocumentBuilder().parse(xmlSrcStream);
 }
  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);
  }
예제 #8
0
 public static Document readXML(String uriXML) throws Exception {
   DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
   dbf.setValidating(false);
   if (uriXML.toUpperCase().trim().indexOf("HTTP:") == -1) {
     return dbf.newDocumentBuilder().parse(new File(uriXML));
   } else return DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(uriXML);
 }
예제 #9
0
  /** Create DOM builder using JAXP libraries. */
  static DocumentBuilder makeBuilder(boolean validate) throws IOException, SAXException {

    DocumentBuilder builder;
    DocumentBuilderFactory factory;

    // create factory according to javax.xml.parsers.SAXParserFactory property
    // or platform default (i.e. com.sun...)
    try {
      factory = DocumentBuilderFactory.newInstance();
      factory.setValidating(validate);
      factory.setNamespaceAware(false);
    } catch (FactoryConfigurationError err) {
      notifyFactoryErr(err, "javax.xml.parsers.DocumentBuilderFactory"); // NOI18N
      throw err;
    }

    try {
      builder = factory.newDocumentBuilder();
    } catch (ParserConfigurationException ex) {
      SAXException sex = new SAXException("Configuration exception."); // NOI18N
      ErrorManager emgr = ErrorManager.getDefault();
      emgr.annotate(sex, ex);
      emgr.annotate(
          sex,
          "Can not create a DOM builder!\nCheck javax.xml.parsers.DocumentBuilderFactory property and the builder library presence on classpath."); // NOI18N
      throw sex;
    }

    return builder;
  }
예제 #10
0
  static {
    try {
      dbf.setNamespaceAware(true);
      db = dbf.newDocumentBuilder();
      xpath.setNamespaceContext(
          new NamespaceContext() {

            @Override
            public Iterator<String> getPrefixes(String namespaceURI) {
              return Arrays.asList("md").iterator();
            }

            @Override
            public String getPrefix(String namespaceURI) {
              return "md";
            }

            @Override
            public String getNamespaceURI(String prefix) {
              return "http://www.osgi.org/xmlns/metatype/v1.1.0";
            }
          });
    } catch (ParserConfigurationException e) {
      e.printStackTrace();
      throw new ExceptionInInitializerError(e);
    }
  }
예제 #11
0
 private void createDOM() throws ParserConfigurationException {
   if (dbf == null) {
     dbf = DocumentBuilderFactory.newInstance();
     db = dbf.newDocumentBuilder();
     dil = (DOMImplementationLS) db.getDOMImplementation();
     dw = dil.createDOMWriter();
   }
 }
예제 #12
0
 /**
  * Create a new DocumentBuilder.
  *
  * <p>WARNING: Check how this is used in this file first before calling!
  */
 private static DocumentBuilder newDocumentBuilder() {
   synchronized (documentBuilderFactory) {
     try {
       return documentBuilderFactory.newDocumentBuilder();
     } catch (ParserConfigurationException e) {
       throw new OXFException(e);
     }
   }
 }
예제 #13
0
  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();
  }
예제 #14
0
  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);
                  }
                }
              }
            }
          }
        }
      }
    }
  }
예제 #15
0
파일: XMLTest.java 프로젝트: quoterman/itis
 /** Возвращает объект 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);
   }
 }
예제 #16
0
 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;
 }
예제 #17
0
  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);
    }
  }
예제 #18
0
 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;
 }
예제 #19
0
  /**
   * 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();
  }
예제 #20
0
  /** @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);
    }
  }
예제 #21
0
파일: vali.java 프로젝트: arlendotcn/ilias
 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();
   }
 }
예제 #22
0
 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);
   }
 }
예제 #23
0
  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);
    }
  }
예제 #24
0
  /**
   * Writes a table to a XML-file
   *
   * @param t - Output Model
   * @param destination - File Destination
   */
  public static void writeXML(Model t, String destination) {

    try {
      // Create the XML document builder, and document that will be used
      DocumentBuilderFactory xmlBuilder = DocumentBuilderFactory.newInstance();
      DocumentBuilder Builder = xmlBuilder.newDocumentBuilder();
      Document xmldoc = Builder.newDocument();

      // create Document node, and get it into the file
      Element Documentnode = xmldoc.createElement("SPREADSHEET");
      xmldoc.appendChild(Documentnode);

      // create element nodes, and their attributes (Cells, and row/column
      // data) and their content
      for (int row = 1; row < t.getRows(); row++) {
        for (int col = 1; col < t.getCols(col); col++) {
          Element cell = xmldoc.createElement("CELL");
          // set attributes
          cell.setAttribute("column", Integer.toString(col));
          cell.setAttribute("row", Integer.toString(col));
          // set content
          cell.appendChild(xmldoc.createTextNode((String) t.getContent(row, col)));
          // append node to document node
          Documentnode.appendChild(cell);
        }
      }
      // Creating a datastream for the DOM tree
      TransformerFactory transformerFactory = TransformerFactory.newInstance();
      Transformer transformer = transformerFactory.newTransformer();
      // Indentation to make the XML file look better
      transformer.setOutputProperty(OutputKeys.METHOD, "xml");
      transformer.setOutputProperty(OutputKeys.INDENT, "yes");
      // remove the java version
      transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
      DOMSource stream = new DOMSource(xmldoc);
      StreamResult target = new StreamResult(new File(destination));
      // write the file
      transformer.transform(stream, target);

    } catch (ParserConfigurationException e) {
      System.out.println("Can't create the XML document builder");
    } catch (TransformerConfigurationException e) {
      System.out.println("Can't create transformer");
    } catch (TransformerException e) {
      System.out.println("Can't write to file");
    }
  }
예제 #25
0
  public static void main(String[] args) {
    try {
      // open existing file
      File xmlFile = new File(userFile);
      DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
      DocumentBuilder dbuild = dbfac.newDocumentBuilder();
      Document doc = dbuild.parse(xmlFile);

      //			DocumentBuilderFactory dbfac2 = DocumentBuilderFactory.newInstance();
      //			DocumentBuilder docBuilder = dbfac2.newDocumentBuilder();
      //			Document doc2 = docBuilder.parse(xmlFile);
      //			doc.getDocumentElement().normalize();

    } catch (Exception e) {
      System.err.println(e.getMessage());
    }
  }
  // Gets the specified XML Schema doc if one is mentioned in the file
  public static File getSchemaFile(File xmlDoc) {
    /** @todo Must be an easier way of doing this... */
    logger.logComment("Getting schema file for: " + xmlDoc);
    try {
      // File xslFile = null;
      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

      DocumentBuilder db = dbf.newDocumentBuilder();

      Document doc = db.parse(xmlDoc);

      return getSchemaFile(doc);
    } catch (Exception e) {
      GuiUtils.showErrorMessage(logger, "Error when looking at the XML file: " + xmlDoc, e, null);
      return null;
    }
  }
예제 #27
0
  /**
   * Obtains DOMImpementaton interface providing a number of methods for performing operations that
   * are independent of any particular DOM instance.
   *
   * @throw DOMException <code>NOT_SUPPORTED_ERR</code> if cannot get DOMImplementation
   * @throw FactoryConfigurationError Application developers should never need to directly catch
   *     errors of this type.
   * @return DOMImplementation implementation
   */
  private static DOMImplementation getDOMImplementation()
      throws DOMException { // can be made public

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

    try {
      return factory.newDocumentBuilder().getDOMImplementation();
    } catch (ParserConfigurationException ex) {
      throw new DOMException(
          DOMException.NOT_SUPPORTED_ERR,
          "Cannot create parser satisfying configuration parameters"); // NOI18N
    } catch (RuntimeException e) {
      // E.g. #36578, IllegalArgumentException. Try to recover gracefully.
      throw (DOMException)
          new DOMException(DOMException.NOT_SUPPORTED_ERR, e.toString()).initCause(e);
    }
  }
예제 #28
0
  /**
   * Unlike the loadXML() method in PApplet, this version works with files that are not in UTF-8
   * format.
   *
   * @nowebref
   */
  public XML(InputStream input, String options)
      throws IOException, ParserConfigurationException, SAXException {
    // this(PApplet.createReader(input), options);  // won't handle non-UTF8
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

    try {
      // Prevent 503 errors from www.w3.org
      factory.setAttribute("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    } catch (IllegalArgumentException e) {
      // ignore this; Android doesn't like it
    }

    factory.setExpandEntityReferences(false);
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document document = builder.parse(new InputSource(input));
    node = document.getDocumentElement();
  }
예제 #29
0
  /**
   * Carica un file XML e ne restituisce un riferimento per DOM
   *
   * @param path - path to xml file
   * @return reference to xml document
   */
  private static Document loadDocument(String path) {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(false);
    try {
      DocumentBuilder db = dbf.newDocumentBuilder();
      Document d = db.parse(new File(path));
      return d;

    } catch (ParserConfigurationException ex) {
      ex.printStackTrace();
      System.exit(10);
    } catch (SAXException sxe) {
      sxe.printStackTrace();
    } catch (IOException ioe) {
      ioe.printStackTrace();
    }
    return null;
  }
예제 #30
0
  /**
   * Reads an XML document from an input source and copies its values into the specified object
   *
   * @param ob The object to receive the values
   * @param source The location of the XML document
   * @throws IOException If there is an error reading the document
   */
  public void readObject(Object ob, InputSource source) throws IOException {
    try {
      // Create a document builder to read the document
      DocumentBuilder builder = factory.newDocumentBuilder();

      // Read the document
      Document doc = builder.parse(source);

      // Get the root element
      Element element = doc.getDocumentElement();

      // Copy the root element into the bean
      readObject(ob, element);
    } catch (SAXException exc) {
      throw new IOException("Error parsing XML document: " + exc.toString());
    } catch (ParserConfigurationException exc) {
      throw new IOException("Error parsing XML document: " + exc.toString());
    }
  }