コード例 #1
0
  public void parseXmlFile(String traFile, String tstFile, String outName) {
    // get the factory
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    resetProcessor();
    try {

      // Using factory get an instance of document builder
      DocumentBuilder db = dbf.newDocumentBuilder();

      // parse using builder to get DOM representation of the XML file
      readedDocument = db.parse(tstFile);
      parseDocumentTst();

      // parse using builder to get DOM representation of the XML file
      readedDocument = db.parse(traFile);
      parseDocumentTra();

      // Sort by int ID to see all easy
      items = sortByValues(items);
      itemsets = sortByValuesArray(itemsets);

      writeToFile(outName);

    } catch (ParserConfigurationException pce) {
      pce.printStackTrace();
    } catch (SAXException se) {
      se.printStackTrace();
    } catch (IOException ioe) {
      ioe.printStackTrace();
    }
  }
コード例 #2
0
 /** Test the generateSaxFragment method. */
 public void testGenerateSaxFragment() throws Exception {
   List beans = new ArrayList(2);
   beans.add(new TestBean("1", "One"));
   beans.add(new TestBean("2", "Two"));
   Map flowContextObject = new HashMap();
   flowContextObject.put("beans", beans);
   Request request = new MockRequest();
   Map objectModel = new HashMap();
   FlowHelper.setContextObject(objectModel, flowContextObject);
   objectModel.put(ObjectModelHelper.REQUEST_OBJECT, request);
   Map contextObjectModel = new HashMap();
   contextObjectModel.put(ContextHelper.CONTEXT_OBJECT_MODEL, objectModel);
   Context context = new DefaultContext(contextObjectModel);
   Source sampleSource =
       new ResourceSource(
           "resource://org/apache/cocoon/forms/datatype/FlowJXPathSelectionListTestCase.source.xml");
   Document sample = parser.parse(sampleSource.getInputStream());
   Element datatypeElement =
       (Element) sample.getElementsByTagNameNS(FormsConstants.DEFINITION_NS, "datatype").item(0);
   Datatype datatype = datatypeManager.createDatatype(datatypeElement, false);
   FlowJXPathSelectionList list =
       new FlowJXPathSelectionList(
           context, "beans", "key", "value", datatype, null, false, null, false);
   DOMBuilder dest = new DOMBuilder();
   list.generateSaxFragment(dest, Locale.ENGLISH);
   Source expectedSource =
       new ResourceSource(
           "resource://org/apache/cocoon/forms/datatype/FlowJXPathSelectionListTestCase.dest.xml");
   Document expected = parser.parse(expectedSource.getInputStream());
   assertEqual("Test if generated list matches expected", expected, dest.getDocument());
 }
コード例 #3
0
ファイル: ModelDSN.java プロジェクト: briskhan/dsnviewer
 public void load() {
   try {
     tinyCads = new ArrayList<TinyCad>();
     DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
     DocumentBuilder db = factory.newDocumentBuilder();
     try {
       doc = db.parse(new File(fname));
     } catch (org.xml.sax.SAXParseException ex) {
       doc =
           db.parse(
               new InputSource(
                   new FileReader(fname) {
                     public String getEncoding() {
                       return "Windows-1251";
                     }
                   }));
     }
     Element root = doc.getDocumentElement();
     for (int i = 0; i < root.getChildNodes().getLength(); i++) {
       if (ModelDSN.debug >= 2)
         System.out.println("Root name: " + root.getChildNodes().item(i).getNodeName());
       if (root.getChildNodes().item(i).getNodeName().equals("TinyCAD")) {
         tc = new TinyCad();
         NodeList nl = root.getChildNodes().item(i).getChildNodes();
         getNames(nl);
         parseRect();
         tinyCads.add(tc);
       }
     }
     fireChangedEvent();
     setChanged(false);
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
コード例 #4
0
  public static Managment ManagmentParsing(String filename)
      throws SAXException, IOException, ParserConfigurationException {

    // create a doc type to read from the xml file menu
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document docInitialData = dBuilder.parse("InitialData.xml");
    Document docOrders = dBuilder.parse("OrdersList.xml");
    Document docMenu = dBuilder.parse("Menu.xml");

    Vector<Chef> Chefs = ChefsParsing(docInitialData);

    Vector<DeliveryPerson> DeliveryPersons = DeliveryPersonsParsing(docInitialData);

    Element Tools = (Element) (docInitialData.getElementsByTagName("Tools").item(0));
    Vector<Kitchen_Tool> KitchenTools = ParsingKitchenTools(Tools);

    Element Ings = (Element) (docInitialData.getElementsByTagName("Ingredients").item(0));
    Vector<Ingredient> Ingredients = ParsingIngredients(Ings);

    WarehouseImpl Warehouse = new WarehouseImpl(Ingredients, KitchenTools);

    Menu m = MenuParsing(docMenu);

    Vector<Order> Orders = OrdersParsing(m, docOrders);

    Element Address = (Element) (docInitialData.getElementsByTagName("Address").item(0));
    Address Res_Address = ParsingAddress(Address);

    return (new Managment(Chefs, Res_Address, DeliveryPersons, Orders, Warehouse, m));
  }
コード例 #5
0
 /**
  * Loads the programming project specified in the projectContents String, which is associated with
  * the language definition file contained in the specified langDefContents. All the blocks
  * contained in projectContents must have an associted block genus defined in langDefContents.
  *
  * <p>If the langDefContents have any workspace settings such as pages or drawers and
  * projectContents has workspace settings as well, the workspace settings within the
  * projectContents will override the workspace settings in langDefContents.
  *
  * <p>NOTE: The language definition contained in langDefContents does not replace the default
  * language definition file set by: setLangDefFilePath() or setLangDefFile().
  *
  * @param projectContents
  * @param langDefContents String XML that defines the language of projectContents
  */
 public void loadProject(String projectContents, String langDefContents) {
   final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
   final DocumentBuilder builder;
   final Document projectDoc;
   final Document langDoc;
   try {
     builder = factory.newDocumentBuilder();
     projectDoc = builder.parse(new InputSource(new StringReader(projectContents)));
     final Element projectRoot = projectDoc.getDocumentElement();
     langDoc = builder.parse(new InputSource(new StringReader(projectContents)));
     final Element langRoot = langDoc.getDocumentElement();
     if (workspaceLoaded) {
       resetWorkspace();
     }
     if (langDefContents == null) {
       loadBlockLanguage(langDefRoot);
     } else {
       loadBlockLanguage(langRoot);
     }
     workspace.loadWorkspaceFrom(projectRoot, langRoot);
     workspaceLoaded = true;
   } catch (ParserConfigurationException e) {
     throw new RuntimeException(e);
   } catch (SAXException e) {
     throw new RuntimeException(e);
   } catch (IOException e) {
     throw new RuntimeException(e);
   }
 }
コード例 #6
0
ファイル: WebXmlParser.java プロジェクト: XiuyeLee/primefaces
  private static Document toDocument(URL url) throws Exception {

    InputStream is = null;

    try {
      // web.xml is optional
      if (url == null) {
        return null;
      }

      is = url.openStream();

      if (is == null) {
        return null;
      }

      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      factory.setValidating(false);
      factory.setNamespaceAware(false);
      factory.setExpandEntityReferences(false);

      try {
        factory.setFeature("http://xml.org/sax/features/namespaces", false);
        factory.setFeature("http://xml.org/sax/features/validation", false);
        factory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
        factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
      } catch (Throwable e) {
        LOG.warning("DocumentBuilderFactory#setFeature not implemented. Skipping...");
      }

      boolean absolute = false;
      try {
        absolute = url.toURI().isAbsolute();
      } catch (URISyntaxException e) {
        // noop
      }

      DocumentBuilder builder = factory.newDocumentBuilder();
      Document document;

      if (absolute) {
        InputSource source = new InputSource(url.toExternalForm());
        source.setByteStream(is);
        document = builder.parse(source);
      } else {
        document = builder.parse(is);
      }

      return document;
    } finally {
      if (is != null) {
        try {
          is.close();
        } catch (IOException e) {
          // ignore
        }
      }
    }
  }
コード例 #7
0
  /** @tests javax.xml.parsers.DocumentBuilderFactory#setExpandEntityReferences(boolean). */
  @TestTargetNew(
      level = TestLevel.COMPLETE,
      notes = "",
      method = "setExpandEntityReferences",
      args = {boolean.class})
  public void test_setExpandEntityReferencesZ() {
    dbf.setExpandEntityReferences(true);
    assertTrue(dbf.isExpandEntityReferences());

    Exception parseException = null;
    DocumentBuilder parser = null;

    try {
      parser = dbf.newDocumentBuilder();
      ValidationErrorHandler errorHandler = new ValidationErrorHandler();
      parser.setErrorHandler(errorHandler);

      Document document = parser.parse(getClass().getResourceAsStream("/recipt.xml"));

      parseException = errorHandler.getFirstException();

      assertNotNull(document);

    } catch (Exception ex) {
      parseException = ex;
    }
    parser.setErrorHandler(null);

    if (parseException != null) {
      fail("Unexpected exception " + parseException.getMessage());
    }

    dbf.setExpandEntityReferences(false);
    assertFalse(dbf.isExpandEntityReferences());
    try {
      parser = dbf.newDocumentBuilder();
      ValidationErrorHandler errorHandler = new ValidationErrorHandler();
      parser.setErrorHandler(errorHandler);

      Document document = parser.parse(getClass().getResourceAsStream("/recipt.xml"));

      parseException = errorHandler.getFirstException();

      assertNotNull(document);

    } catch (Exception ex) {
      parseException = ex;
    }
    parser.setErrorHandler(null);

    if (parseException != null) {
      fail("Unexpected exception " + parseException.getMessage());
    }
  }
コード例 #8
0
  /**
   * Create some content in the context of a given document
   *
   * @return
   *     <ul>
   *       <li>A {@link DocumentFragment} if <code>text</code> is well-formed.
   *       <li><code>null</code>, if <code>text</code> is plain text or not well formed
   *     </ul>
   */
  static final DocumentFragment createContent(Document doc, String text) {

    // Text might hold XML content
    if (text != null && text.contains("<")) {
      DocumentBuilder builder = builder();

      try {

        // [#128] Trimming will get rid of leading and trailing whitespace, which would
        // otherwise cause a HIERARCHY_REQUEST_ERR raised by the parser
        text = text.trim();

        // There is a processing instruction. We can safely assume
        // valid XML and parse it as such
        if (text.startsWith("<?xml")) {
          Document parsed = builder.parse(new InputSource(new StringReader(text)));
          DocumentFragment fragment = parsed.createDocumentFragment();
          fragment.appendChild(parsed.getDocumentElement());

          return (DocumentFragment) doc.importNode(fragment, true);
        }

        // Any XML document fragment. To be on the safe side, fragments
        // are wrapped in a dummy root node
        else {
          String wrapped = "<dummy>" + text + "</dummy>";
          Document parsed = builder.parse(new InputSource(new StringReader(wrapped)));
          DocumentFragment fragment = parsed.createDocumentFragment();
          NodeList children = parsed.getDocumentElement().getChildNodes();

          // appendChild removes children also from NodeList!
          while (children.getLength() > 0) {
            fragment.appendChild(children.item(0));
          }

          return (DocumentFragment) doc.importNode(fragment, true);
        }
      }

      // This does not occur
      catch (IOException ignore) {
      }

      // The XML content is invalid
      catch (SAXException ignore) {
      }
    }

    // Plain text or invalid XML
    return null;
  }
コード例 #9
0
ファイル: AnalyzeSqlXml.java プロジェクト: naily/nutzmore
  private static Document[] getOtherSqlDocs(Document doc) {
    NodeList nodeList = doc.getElementsByTagName("include"); // 得到所有标签为sql的node
    // Document[] docs=new Document[nodeList.getLength()];
    List<Document> docs = new ArrayList<Document>();
    for (int i = 0; i < nodeList.getLength(); i++) {
      Node node = nodeList.item(i); // 得到其中的一个
      NamedNodeMap nodeMap = node.getAttributes();
      String filePath = nodeMap.getNamedItem("file").getNodeValue(); // 得到file属性
      try {
        builder = factory.newDocumentBuilder();
        builder.setEntityResolver(
            new EntityResolver() {
              public InputSource resolveEntity(String publicId, String systemId)
                  throws SAXException, IOException {
                return new InputSource(new StringReader(""));
              }
            });
        if (filePath.indexOf("*") == -1) {
          URL url = classLoader.getResource(filePath);
          docs.add(builder.parse(url.toString()));
        } else {
          String baseFilePath = classLoader.getResource("").getPath();

          if (filePath.indexOf("/") != -1) {
            baseFilePath = baseFilePath + filePath.substring(0, filePath.lastIndexOf("/"));
          }
          baseFilePath = java.net.URLDecoder.decode(baseFilePath, "utf-8");
          File baseFile = new File(baseFilePath);
          if (!baseFile.isDirectory()) {
            throw new IllegalArgumentException(baseFilePath + "不是一个有效的目录!");
          }
          String fileLikeName = filePath.substring(filePath.lastIndexOf("/") + 1);

          File[] files = baseFile.listFiles();
          for (int j = 0; j < files.length; j++) {
            if (BASESQLFILE.equals(files[j].getName())) {
              continue;
            }
            if (files[j].getName().indexOf(fileLikeName.replaceAll("\\*", "")) != -1) {
              docs.add(builder.parse(files[j]));
            }
          }
        }
      } catch (Exception e) {
        throw new RuntimeException("在解析文件:" + filePath + "出现异常", e);
      }
    }
    Document[] documents = new Document[docs.size()];
    return docs.toArray(documents);
  }
コード例 #10
0
  /** @tests javax.xml.parsers.DocumentBuilderFactory#setIgnoringComments(boolean). */
  @TestTargetNew(
      level = TestLevel.COMPLETE,
      notes = "",
      method = "setIgnoringComments",
      args = {boolean.class})
  public void test_setIgnoringCommentsZ() {
    commentElements.clear();

    dbf.setIgnoringComments(true);
    assertTrue(dbf.isIgnoringComments());

    try {
      DocumentBuilder parser = dbf.newDocumentBuilder();

      Document document = parser.parse(getClass().getResourceAsStream("/recipt.xml"));

      goThroughDocument((Node) document, "");
      assertFalse(commentElements.contains("comment1"));
      assertFalse(commentElements.contains("comment2"));

    } catch (IOException e) {
      fail("Unexpected IOException " + e.getMessage());
    } catch (ParserConfigurationException e) {
      fail("Unexpected ParserConfigurationException " + e.getMessage());
    } catch (SAXException e) {
      fail("Unexpected SAXException " + e.getMessage());
    }

    commentElements.clear();

    dbf.setIgnoringComments(false);
    assertFalse(dbf.isIgnoringComments());

    try {
      DocumentBuilder parser = dbf.newDocumentBuilder();

      Document document = parser.parse(getClass().getResourceAsStream("/recipt.xml"));

      goThroughDocument((Node) document, "");
      assertTrue(commentElements.contains("comment1"));
      assertTrue(commentElements.contains("comment2"));

    } catch (IOException e) {
      fail("Unexpected IOException " + e.getMessage());
    } catch (ParserConfigurationException e) {
      fail("Unexpected ParserConfigurationException " + e.getMessage());
    } catch (SAXException e) {
      fail("Unexpected SAXException " + e.getMessage());
    }
  }
コード例 #11
0
  public KodiScraper parseScraper(KodiScraper scraper, List<File> common) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder parser = factory.newDocumentBuilder();

    File scraperFile = new File(scraper.getFolder(), scraper.getScraperXml());
    String xmlFile = FileUtils.readFileToString(scraperFile, "UTF-8");
    xmlFile = KodiUtil.fixXmlHeader(xmlFile);

    Document xml;
    try {
      InputStream stream = new ByteArrayInputStream(xmlFile.getBytes(StandardCharsets.UTF_8));
      xml = parser.parse(stream);
    } catch (SAXException e) {
      LOGGER.warn("Error parsing " + scraperFile + " - trying fallback");
      // eg FilmAffinity.com scraper
      // replace all known entities with their unicode notation
      // this fixes the "entity 'Iacute' was referenced, but not declared" parsing problems, since
      // we do not have to add doctype entity declarations
      // might replace too much; so this is only a fallback
      for (String[] ent : EntityArrays.ISO8859_1_UNESCAPE()) {
        xmlFile = xmlFile.replace(ent[0], ent[1]);
      }
      InputStream stream = new ByteArrayInputStream(xmlFile.getBytes(StandardCharsets.UTF_8));
      xml = parser.parse(stream);
    }

    Element docEl = xml.getDocumentElement();
    NodeList nl = docEl.getChildNodes();

    for (int i = 0; i < nl.getLength(); i++) {
      Node n = nl.item(i);
      if (n.getNodeType() == Node.ELEMENT_NODE) {
        Element el = (Element) n;
        ScraperFunction func = new ScraperFunction();
        func.setName(el.getNodeName());
        func.setClearBuffers(parseBoolean(el.getAttribute("clearbuffers"), true));
        func.setAppendBuffer(parseAppendBuffer(el.getAttribute("dest")));
        func.setDest(parseInt(el.getAttribute("dest")));
        scraper.addFunction(func);

        // functions contain regexp expressions, so let's get those.
        processRegexps(func, el);
      }
    }

    // get all common scraper functions
    readScraperFunctions(scraper, common);

    return scraper;
  }
コード例 #12
0
  // We read the repositories from the file:
  //
  public boolean readData() throws KettleException {
    // Clear the information
    //
    clear();

    File file = new File(getKettleLocalRepositoriesFile());
    if (!file.exists() || !file.isFile()) {
      log.logDetailed(
          BaseMessages.getString(
              PKG, "RepositoryMeta.Log.NoRepositoryFileInLocalDirectory", file.getAbsolutePath()));
      file = new File(getKettleUserRepositoriesFile());
      if (!file.exists() || !file.isFile()) {
        return true; // nothing to read!
      }
    }

    log.logBasic(
        BaseMessages.getString(PKG, "RepositoryMeta.Log.ReadingXMLFile", file.getAbsoluteFile()));

    DocumentBuilderFactory dbf;
    DocumentBuilder db;
    Document doc;

    try {
      // Check and open XML document
      dbf = DocumentBuilderFactory.newInstance();
      db = dbf.newDocumentBuilder();
      try {
        doc = db.parse(file);
      } catch (FileNotFoundException ef) {
        InputStream is =
            getClass().getResourceAsStream("/org/pentaho/di/repository/repositories.xml");
        if (is != null) {
          doc = db.parse(is);
        } else {
          throw new KettleException(
              BaseMessages.getString(
                  PKG, "RepositoryMeta.Error.OpeningFile", file.getAbsoluteFile()),
              ef);
        }
      }
      parseRepositoriesDoc(doc);
    } catch (Exception e) {
      throw new KettleException(BaseMessages.getString(PKG, "RepositoryMeta.Error.ReadingInfo"), e);
    }

    return true;
  }
コード例 #13
0
ファイル: IrXmlReader.java プロジェクト: hallvard/caltoopia
  public Namespace readNamespace(String path) {
    try {
      File fXmlFile = new File(path);
      DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
      DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
      Document doc = dBuilder.parse(fXmlFile);
      doc.getDocumentElement().normalize();

      String topTag = doc.getDocumentElement().getNodeName();

      if (topTag.equals("Namespace")) {
        Namespace result = createNamespace(doc.getDocumentElement());
        for (ForwardDeclaration decl : forwardDeclarationMap.keySet()) {
          decl.setDeclaration((Declaration) findIrObject(forwardDeclarationMap.get(decl)));
        }
        return result;
      } else {
        throw new RuntimeException("Invalid top tag in XML ir document");
      }

      // As a last step, patch the forward declarations

    } catch (Exception e) {
      System.err.println("[IrXmlReader. Error reading '" + path + "' message = " + e.getMessage());
      e.printStackTrace();
      return null;
    }
  }
コード例 #14
0
ファイル: IrXmlReader.java プロジェクト: hallvard/caltoopia
  public AbstractActor readActor(String path) {
    try {
      File fXmlFile = new File(path);
      DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
      DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
      Document doc = dBuilder.parse(fXmlFile);
      doc.getDocumentElement().normalize();

      String topTag = doc.getDocumentElement().getNodeName();
      AbstractActor result;

      if (topTag.equals("Actor")) {
        result = createActor(doc.getDocumentElement());
      } else if (topTag.equals("Network")) {
        result = createNetwork(doc.getDocumentElement());
      } else if (topTag.equals("ExternalActor")) {
        result = createExternalActor(doc.getDocumentElement());
      } else {
        throw new RuntimeException("Invalid top tag in XML ir document");
      }

      // As a last step, patch the forward declarations
      for (ForwardDeclaration decl : forwardDeclarationMap.keySet()) {
        decl.setDeclaration((Declaration) findIrObject(forwardDeclarationMap.get(decl)));
      }

      return result;
    } catch (Exception x) {
      System.err.println("[ActorDirectory]ÊError reading '" + path + "' x " + x.getMessage());
      return null;
    }
  }
コード例 #15
0
  public ArrayList<Entity> getEntitiesFromFile(String filePath) {
    ArrayList<Entity> entities = new ArrayList<>();
    try {
      d = db.parse(filePath);

      NodeList entityMentions = d.getElementsByTagName("entity_mention");
      for (int i = 0; i < entityMentions.getLength(); i++) {
        Element entityMention = (Element) entityMentions.item(i);
        NodeList heads = entityMention.getElementsByTagName("head");
        Element head = (Element) heads.item(0);
        NodeList charseqs = head.getElementsByTagName("charseq");
        Element charseq = (Element) charseqs.item(0);
        int start = Integer.parseInt(charseq.getAttribute("START"));
        int end = Integer.parseInt(charseq.getAttribute("END"));
        String value = charseq.getFirstChild().getNodeValue();
        // value = value.replaceAll("\n", "");
        String id = entityMention.getAttribute("ID");
        Element entityParent = (Element) entityMention.getParentNode();
        String type = entityParent.getAttribute("TYPE");
        // String subType = entityParent.getAttribute("SUBTYPE");
        Entity entity = new Entity(value, start, end, type, id);
        entities.add(entity);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return entities;
  }
コード例 #16
0
  private void loadExcludes() throws ParserConfigurationException, IOException, SAXException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();

    InputStream is = null;

    if (excludesFile == null) {
      is = config.getServletContext().getResourceAsStream(excludesFileName);
    } else if (excludesFile.exists() && excludesFile.canRead()) {
      is = excludesFile.toURI().toURL().openStream();
    }

    if (is == null) {
      throw new IllegalStateException(
          "Cannot load excludes configuration file \""
              + excludesFileName
              + "\" as specified in \"sitemesh.xml\" or \"sitemesh-default.xml\"");
    }

    Document document = builder.parse(is);
    Element root = document.getDocumentElement();
    NodeList sections = root.getChildNodes();

    // Loop through child elements of root node looking for the <excludes> block
    for (int i = 0; i < sections.getLength(); i++) {
      if (sections.item(i) instanceof Element) {
        Element curr = (Element) sections.item(i);
        if ("excludes".equalsIgnoreCase(curr.getTagName())) {
          loadExcludeUrls(curr.getChildNodes());
        }
      }
    }
  }
コード例 #17
0
ファイル: XmlStringUtil.java プロジェクト: huu0510/z-pec
 /**
  * Get value out of a specified element's name in XML file
  *
  * @param xmlFile XML File to look at
  * @param elementName Element name, in which the value is wanted
  * @return (String) Element's value
  * @throws IOException
  */
 public static String parseXmlFile(String xmlFile, String elementName) throws IOException {
   DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
   String output = null;
   try {
     File file = new File(xmlFile);
     DocumentBuilder db = dbf.newDocumentBuilder();
     Document doc = db.parse(file);
     doc.getDocumentElement().normalize();
     NodeList nodeLst = doc.getDocumentElement().getElementsByTagName("key");
     for (int i = 0; i < nodeLst.getLength(); i++) {
       Node currentNode = nodeLst.item(i);
       Element currentElement = (Element) currentNode;
       String keyName = currentElement.getAttribute("name");
       if (!keyName.equals(elementName)) {
         continue;
       } else {
         Element value = (Element) currentElement.getElementsByTagName("value").item(0);
         output = value.getChildNodes().item(0).getNodeValue();
         break;
       }
     }
   } catch (ParserConfigurationException pce) {
     logger.warn(pce);
   } catch (SAXException se) {
     logger.warn(se);
   }
   return output;
 }
 private void checkBomVersionInPom(String xml) {
   DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
   DocumentBuilder builder;
   Document doc = null;
   try {
     builder = factory.newDocumentBuilder();
     doc = builder.parse(new InputSource(new StringReader(xml)));
   } catch (SAXException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   } catch (ParserConfigurationException e1) {
     // TODO Auto-generated catch block
     e1.printStackTrace();
   }
   XPathFactory xPathfactory = XPathFactory.newInstance();
   XPath xpath = xPathfactory.newXPath();
   XPathExpression expr = null;
   String bom_version = null;
   try {
     expr = xpath.compile("/project/properties/version.jboss.bom");
     bom_version = (String) expr.evaluate(doc, XPathConstants.STRING);
   } catch (XPathExpressionException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
   assertEquals(
       "jboss bom version in pom differs from the one given by wizard", version, bom_version);
 }
コード例 #19
0
  public NodeList getOQasNodeList()
      throws SAXException, ParserConfigurationException, XPathExpressionException {
    NodeList result = null;
    if (oqUrl == null) {
      logger.warn("OQ.url not found. Synchronization impossible.");
      trace.append("Синхронизация невозможна: OQ.url не указан.");
      return result;
    }
    try {
      URLConnection oqc = oqUrl.openConnection();
      DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
      domFactory.setNamespaceAware(true);
      DocumentBuilder builder = domFactory.newDocumentBuilder();
      Document doc = builder.parse(oqc.getInputStream());
      XPath xpath = XPathFactory.newInstance().newXPath();
      XPathExpression expr = xpath.compile("/root/projects/project");
      result = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
    } catch (IOException e) { // обрабатываем только IOException - остальные выбрасываем наверх
      logger.error("oq project sync error: ", e);
      trace
          .append(
              "Синхронизация прервана из-за ошибки ввода/вывода при попытке получить и прочитать файл "
                  + "синхронизации: ")
          .append(e.getMessage())
          .append("\n");
    }

    return result;
  }
コード例 #20
0
 /** get all the categories of all tv programs */
 public static ArrayList<OnlineVideo> getAllCategory(final Context context) {
   ArrayList<OnlineVideo> result = new ArrayList<OnlineVideo>();
   DocumentBuilderFactory docBuilderFactory = null;
   DocumentBuilder docBuilder = null;
   Document doc = null;
   try {
     docBuilderFactory = DocumentBuilderFactory.newInstance();
     docBuilder = docBuilderFactory.newDocumentBuilder();
     // xml file is set in 'assets' folder
     doc = docBuilder.parse(context.getResources().getAssets().open("online.xml"));
     // root element
     Element root = doc.getDocumentElement();
     NodeList nodeList = root.getElementsByTagName("category");
     for (int i = 0; i < nodeList.getLength(); i++) {
       Node node = nodeList.item(i); // category
       OnlineVideo ov = new OnlineVideo();
       NamedNodeMap attr = node.getAttributes();
       ov.title = attr.getNamedItem("name").getNodeValue();
       ov.id = attr.getNamedItem("id").getNodeValue();
       ov.category = 1;
       ov.level = 2;
       ov.is_category = true;
       result.add(ov);
       // Read Node
     }
   } catch (IOException e) {
   } catch (SAXException e) {
   } catch (ParserConfigurationException e) {
   } finally {
     doc = null;
     docBuilder = null;
     docBuilderFactory = null;
   }
   return result;
 }
コード例 #21
0
  /**
   * Read parse trees from a Reader.
   *
   * @param filename
   * @param in The <code>Reader</code>
   * @param simplifiedTagset If `true`, convert part-of-speech labels to a simplified version of the
   *     EAGLES tagset, where the tags do not include extensive morphological analysis
   * @param aggressiveNormalization Perform aggressive "normalization" on the trees read from the
   *     provided corpus documents: split multi-word tokens into their constituent words (and infer
   *     parts of speech of the constituent words).
   * @param retainNER Retain NER information in preterminals (for later use in
   *     `MultiWordPreprocessor) and add NER-specific parents to single-word NE tokens
   * @param detailedAnnotations Retain detailed tree node annotations. These annotations on parse
   *     tree constituents may be useful for e.g. training a parser.
   */
  public SpanishXMLTreeReader(
      String filename,
      Reader in,
      boolean simplifiedTagset,
      boolean aggressiveNormalization,
      boolean retainNER,
      boolean detailedAnnotations) {
    TreebankLanguagePack tlp = new SpanishTreebankLanguagePack();

    this.simplifiedTagset = simplifiedTagset;
    this.detailedAnnotations = detailedAnnotations;

    stream = new ReaderInputStream(in, tlp.getEncoding());
    treeFactory = new LabeledScoredTreeFactory();
    treeNormalizer =
        new SpanishTreeNormalizer(simplifiedTagset, aggressiveNormalization, retainNER);

    DocumentBuilder parser = XMLUtils.getXmlParser();
    try {
      final Document xml = parser.parse(stream);
      final Element root = xml.getDocumentElement();
      sentences = root.getElementsByTagName(NODE_SENT);
      sentIdx = 0;

    } catch (SAXException e) {
      System.err.println("Parse exception while reading " + filename);
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
コード例 #22
0
ファイル: TestBase.java プロジェクト: liuxing9848/pokerth
  @Before
  public void dbInit() throws Exception {
    String configFileName = System.getProperty("user.home");
    if (System.getProperty("os.name").toLowerCase().indexOf("linux") > -1) {
      configFileName += "/.pokerth/config.xml";
    } else {
      configFileName += "/AppData/Roaming/pokerth/config.xml";
    }
    File file = new File(configFileName);
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse(file);
    doc.getDocumentElement().normalize();
    Element configNode = (Element) doc.getElementsByTagName("Configuration").item(0);

    Element dbAddressNode = (Element) configNode.getElementsByTagName("DBServerAddress").item(0);
    String dbAddress = dbAddressNode.getAttribute("value");

    Element dbUserNode = (Element) configNode.getElementsByTagName("DBServerUser").item(0);
    String dbUser = dbUserNode.getAttribute("value");

    Element dbPasswordNode = (Element) configNode.getElementsByTagName("DBServerPassword").item(0);
    String dbPassword = dbPasswordNode.getAttribute("value");

    Element dbNameNode = (Element) configNode.getElementsByTagName("DBServerDatabaseName").item(0);
    String dbName = dbNameNode.getAttribute("value");

    final String dbUrl = "jdbc:mysql://" + dbAddress + ":3306/" + dbName;
    Class.forName("com.mysql.jdbc.Driver").newInstance();
    dbConn = DriverManager.getConnection(dbUrl, dbUser, dbPassword);
  }
コード例 #23
0
  @Test
  public void testFieldHasMatchingUserValues() throws Exception {
    LOG.info("testFieldHasMatchingUserValues");
    DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();

    XPath xpath = XPathFactory.newInstance().newXPath();
    Document doc = db.parse(this.getClass().getResourceAsStream(SAMPLE_EDOC_XML));
    // enumerate all fields
    final String fieldDefs = "/edlContent/edl/field/display/values";
    NodeList nodes = (NodeList) xpath.evaluate(fieldDefs, doc, XPathConstants.NODESET);

    for (int i = 0; i < nodes.getLength(); i++) {
      Node node = nodes.item(i);
      String name = (String) xpath.evaluate("../../@name", node, XPathConstants.STRING);
      LOG.debug("Name: " + name);
      LOG.debug("Value: " + node.getFirstChild().getNodeValue());
      final String expr =
          "/edlContent/data/version[@current='true']/fieldEntry[@name=current()/../../@name and value=current()]";
      NodeList matchingUserValues = (NodeList) xpath.evaluate(expr, node, XPathConstants.NODESET);
      LOG.debug(matchingUserValues + "");
      LOG.debug(matchingUserValues.getLength() + "");
      if ("gender".equals(name)) {
        assertTrue("Matching values > 0", matchingUserValues.getLength() > 0);
      }
      for (int j = 0; j < matchingUserValues.getLength(); j++) {
        LOG.debug(matchingUserValues.item(j).getFirstChild().getNodeValue());
      }
    }
  }
コード例 #24
0
 /**
  * load.
  *
  * @param resource a {@link org.springframework.core.io.Resource} object.
  * @return a {@link java.util.List} object.
  */
 public List<ReconfigBeanDefinitionHolder> load(Resource resource) {
   List<ReconfigBeanDefinitionHolder> holders = new ArrayList<ReconfigBeanDefinitionHolder>();
   try {
     InputStream inputStream = resource.getInputStream();
     try {
       InputSource inputSource = new InputSource(inputStream);
       DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
       DocumentBuilder docBuilder = factory.newDocumentBuilder();
       Document doc = docBuilder.parse(inputSource);
       Element root = doc.getDocumentElement();
       NodeList nl = root.getChildNodes();
       BeanDefinitionParser parser = new BeanDefinitionParser();
       for (int i = 0; i < nl.getLength(); i++) {
         Node node = nl.item(i);
         if (node instanceof Element) {
           Element ele = (Element) node;
           ReconfigBeanDefinitionHolder holder = parser.parseBeanDefinitionElement(ele);
           holders.add(holder);
         }
       }
     } finally {
       if (null != inputStream) {
         inputStream.close();
       }
     }
   } catch (Exception ex) {
     throw new RuntimeException(
         "IOException parsing XML document from " + resource.getDescription(), ex);
   }
   return holders;
 }
コード例 #25
0
ファイル: XmlHelper.java プロジェクト: MPDL-Collections/INGe
  /**
   * Creates new org.w3c.dom.Document with Traversing possibility
   *
   * @param is <code>InputSource</code>
   * @return org.w3c.dom.Document
   * @throws CitationStyleManagerException
   */
  public static Document parseDocumentForTraversing(InputSource is)
      throws CitationStyleManagerException {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    DocumentBuilder parser;
    try {
      parser = dbf.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
      throw new CitationStyleManagerException("Cannot create DocumentBuilder:", e);
    }

    // Check for the traversal module
    DOMImplementation impl = parser.getDOMImplementation();
    if (!impl.hasFeature("traversal", "2.0")) {
      throw new CitationStyleManagerException(
          "A DOM implementation that supports traversal is required.");
    }
    Document doc;
    try {
      doc = parser.parse(is);
    } catch (Exception e) {
      throw new CitationStyleManagerException("Cannot parse InputSource to w3c document:", e);
    }

    return doc;
  }
コード例 #26
0
 public BMCreateButtonResponseType(Object xmlSoap)
     throws IOException, SAXException, ParserConfigurationException {
   super(xmlSoap);
   DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
   DocumentBuilder builder = builderFactory.newDocumentBuilder();
   InputSource inStream = new InputSource();
   inStream.setCharacterStream(new StringReader((String) xmlSoap));
   Document document = builder.parse(inStream);
   NodeList nodeList = null;
   String xmlString = "";
   if (document.getElementsByTagName("Website").getLength() != 0) {
     if (!isWhitespaceNode(document.getElementsByTagName("Website").item(0))) {
       this.Website = (String) document.getElementsByTagName("Website").item(0).getTextContent();
     }
   }
   if (document.getElementsByTagName("Email").getLength() != 0) {
     if (!isWhitespaceNode(document.getElementsByTagName("Email").item(0))) {
       this.Email = (String) document.getElementsByTagName("Email").item(0).getTextContent();
     }
   }
   if (document.getElementsByTagName("Mobile").getLength() != 0) {
     if (!isWhitespaceNode(document.getElementsByTagName("Mobile").item(0))) {
       this.Mobile = (String) document.getElementsByTagName("Mobile").item(0).getTextContent();
     }
   }
   if (document.getElementsByTagName("HostedButtonID").getLength() != 0) {
     if (!isWhitespaceNode(document.getElementsByTagName("HostedButtonID").item(0))) {
       this.HostedButtonID =
           (String) document.getElementsByTagName("HostedButtonID").item(0).getTextContent();
     }
   }
 }
コード例 #27
0
ファイル: SVGParser.java プロジェクト: NwAurion/kosmor
  /**
   * 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;
  }
コード例 #28
0
  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);
  }
コード例 #29
0
ファイル: ReadXML.java プロジェクト: valentinedwv/incf-dai
  /**
   * Get root element from XML String
   *
   * @param arg XML String
   * @return Root Element
   * @throws ParserConfigurationException
   * @throws SAXException
   * @throws IOException
   */
  public static Element getDocumentElementFromString(String arg)
      throws ParserConfigurationException, SAXException, IOException {

    System.out.println("1 - before: " + arg);

    String xml = arg.trim().replaceFirst("^([\\W]+)<", "<");

    DocumentBuilderFactory dbf;
    System.out.println("2 - after: " + xml);
    DocumentBuilder db;
    System.out.println("3");
    Document document;
    System.out.println("4");
    dbf = DocumentBuilderFactory.newInstance();
    System.out.println("5");
    db = dbf.newDocumentBuilder();
    System.out.println("6");
    document = db.parse(new InputSource(new StringReader(xml)));
    System.out.println("7");
    Element element = document.getDocumentElement();
    System.out.println("8");

    db = null;
    dbf = null;
    document = null;

    return element;
  }
コード例 #30
0
ファイル: XMLRecognizer.java プロジェクト: tm3553881/tesweb
  public static String RecogniseFromXml(byte[] bin) {

    String tranCode = "";
    String xmlStr = new String(bin);

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    Element theTranCode = null, root = null;
    try {
      factory.setIgnoringElementContentWhitespace(true);

      DocumentBuilder db = factory.newDocumentBuilder();

      final byte[] bytes = xmlStr.getBytes();
      final ByteArrayInputStream is = new ByteArrayInputStream(bytes);
      final InputSource source = new InputSource(is);

      Document xmldoc = db.parse(source);
      root = xmldoc.getDocumentElement();
      theTranCode = (Element) selectSingleNode("/root/head/transid", root);
      // Element nameNode = (Element) theTranCode.getElementsByTagName("price").item(0);
      if (theTranCode != null) {
        tranCode = theTranCode.getFirstChild().getNodeValue();
      } else {
        System.out.println("获取 /root/head/transid 失败!");
      }
      // System.out.println(tranCode);
    } catch (ParserConfigurationException e) {
      e.printStackTrace();
    } catch (SAXException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return tranCode;
  }