Java 类org.jdom2.input.SAXBuilder 实例源码

项目:goobi-viewer-connector    文件:Utils.java   
/**
 * Create a JDOM document from an XML string.
 * 
 * @param string
 * @param encoding
 * @return
 * @throws IOException
 * @throws JDOMException
 * @should build document correctly
 */
public static Document getDocumentFromString(String string, String encoding) throws JDOMException, IOException {
    if (encoding == null) {
        encoding = DEFAULT_ENCODING;
    }

    byte[] byteArray = null;
    try {
        byteArray = string.getBytes(encoding);
    } catch (UnsupportedEncodingException e) {
    }
    ByteArrayInputStream baos = new ByteArrayInputStream(byteArray);
    SAXBuilder builder = new SAXBuilder();
    Document document = builder.build(baos);

    return document;
}
项目:goobi-viewer-indexer    文件:Utils.java   
/**
 * Create a JDOM document from an XML string.
 *
 * @param string
 * @return
 * @throws IOException
 * @throws JDOMException
 * @should build document correctly
 */
public static Document getDocumentFromString(String string, String encoding) throws JDOMException, IOException {
    if (string == null) {
        throw new IllegalArgumentException("string may not be null");
    }
    if (encoding == null) {
        encoding = "UTF-8";
    }

    byte[] byteArray = null;
    try {
        byteArray = string.getBytes(encoding);
    } catch (UnsupportedEncodingException e) {
    }
    ByteArrayInputStream baos = new ByteArrayInputStream(byteArray);

    // Reader reader = new StringReader(hOCRText);
    SAXBuilder builder = new SAXBuilder();
    Document document = builder.build(baos);

    return document;
}
项目:Java-Data-Science-Cookbook    文件:TestJdom.java   
public void parseXml(String fileName){
    SAXBuilder builder = new SAXBuilder();
    File file = new File(fileName);
    try {
        Document document = (Document) builder.build(file);
        Element rootNode = document.getRootElement();
        List list = rootNode.getChildren("author");
        for (int i = 0; i < list.size(); i++) {
            Element node = (Element) list.get(i);
            System.out.println("First Name : " + node.getChildText("firstname"));
            System.out.println("Last Name : " + node.getChildText("lastname"));
        }
    } catch (IOException io) {
        System.out.println(io.getMessage());
    } catch (JDOMException jdomex) {
        System.out.println(jdomex.getMessage());
    }



}
项目:bibliometrics    文件:BibliometricReportDisplayServlet.java   
public void doGetPost(MCRServletJob job) throws Exception {
    HttpServletRequest req = job.getRequest();
    String path = job.getRequest().getPathInfo().substring(1);
    LOGGER.info(path);
    boolean b = tryLogin(path.substring(0, 6), path.substring(6), false);
    if (b) {
        org.apache.shiro.subject.Subject currentUser = SecurityUtils.getSubject();
        if (currentUser.hasRole("client")) {
            String hash = req.getUserPrincipal().getName();
            File reportFile = new File(resultsDir + "/" + hash.substring(0, 6), "report.xml");
            SAXBuilder builder = new SAXBuilder();
            Document document = builder.build(reportFile);
            getLayoutService().doLayout(job.getRequest(), job.getResponse(), new MCRJDOMContent(document));
            }
    }
}
项目:ctsms    文件:ClamlImporter.java   
private long parse(String fileName, String lang, ClamlClassProcessor processor) throws Exception {
    processor.reset();
    jobOutput.println("reading from file " + fileName);
    Element root = (new SAXBuilder()).build(new File(fileName)).getRootElement();
    parseClassKinds(root);
    parseModifiers(root);
    parseModifierClasses(root);
    parseClasses(root);
    long categoryClassCount = 0l;
    Iterator<String> kindsIt = classKinds.keySet().iterator();
    while (kindsIt.hasNext()) {
        String kind = kindsIt.next();
        Map<String, Element> codeMap = classKinds.get(kind);
        Iterator<String> codesIt = codeMap.keySet().iterator();
        while (codesIt.hasNext()) {
            String code = codesIt.next();
            categoryClassCount += processor.processClass(kind, code, codeMap.get(code), classKinds, modifierClasses, lang);
        }
    }
    jobOutput.println(categoryClassCount + " ClaML categories processed");
    processor.postProcess();
    return categoryClassCount;
}
项目:lexeme    文件:LeXeMerger.java   
/**
 * Merges a given XML file with a patch. This API is designed for CobiGen
 * @see com.github.maybeec.lexeme.LeXeMerger#merge(Element, Element, ConflictHandlingType)
 * @param base
 *            File
 * @param patch
 *            String
 * @param charSet
 *            target charset of the file to be read and write
 * @param conflictHandling
 *            {@link ConflictHandlingType} specifying how conflicts will be handled during the merge
 *            process. If null the default for this LeXeMerger will be used
 * @return Document the merged result of base and patch
 * @throws XMLMergeException
 *             when the Documents can't be properly merged
 * @author sholzer (23.04.2015)
 */
public Document merge(File base, String patch, String charSet, ConflictHandlingType conflictHandling)
    throws XMLMergeException {
    if (conflictHandling == null) {
        conflictHandling = conflictHandlingType;
    }
    try {
        SAXBuilder builder = new SAXBuilder(XMLReaders.NONVALIDATING);
        builder.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        String baseString = JDom2Util.getInstance().readFile(base.getPath(), charSet);
        Document baseDoc =
            builder.build(new InputSource(new BufferedReader(new StringReader(baseString))));
        Document patchDoc = builder.build(new InputSource(new BufferedReader(new StringReader(patch))));
        return merge(baseDoc, patchDoc, conflictHandling);
    } catch (IOException | JDOMException e) {
        logger.error("Caught unexcpected {}:{}", e.getClass().getName(), e.getMessage());
        throw new XMLMergeException(e.getMessage());
    }

}
项目:lexeme    文件:ElementMergerImplTest.java   
/**
 * Tests if the Attribute order is preserved while parsing
 *
 * @author sholzer (04.05.2015)
 * @throws IOException
 *             when file not found (i guess...)
 * @throws JDOMException
 *             when something else goes wrong
 */
@Test
public void testAttributeOrdering() throws JDOMException, IOException {

    String path = "src/test/resources/";
    String filePath = path + "ConceptTest.xml";
    SAXBuilder builder = new SAXBuilder();
    Document doc = builder.build(filePath);

    Element element = doc.getRootElement();
    List<org.jdom2.Attribute> attributes = element.getAttributes();
    System.out.println(attributes);
    assertTrue(attributes.toString(), attributes.get(0).getName().equals("b"));
    assertTrue(attributes.toString(), attributes.get(1).getName().equals("c"));
    assertTrue(attributes.toString(), attributes.get(2).getName().equals("a"));
}
项目:HELM2NotationToolkit    文件:MonomerParser.java   
public static List<Monomer> getMonomerList(String monomerXMLString)
    throws JDOMException, IOException, MonomerException, CTKException, ChemistryException {
  List<Monomer> l = new ArrayList<Monomer>();
  if (null != monomerXMLString && monomerXMLString.length() > 0) {
    SAXBuilder builder = new SAXBuilder();
    ByteArrayInputStream bais = new ByteArrayInputStream(
        monomerXMLString.getBytes());
    Document doc = builder.build(bais);
    Element root = doc.getRootElement();

    List monomers = root.getChildren();
    Iterator it = monomers.iterator();
    while (it.hasNext()) {
      Element monomer = (Element) it.next();
      Monomer m = getMonomer(monomer);
      if (MonomerParser.validateMonomer(m)) {
        l.add(m);
      }
    }
  }
  return l;
}
项目:HealthCheckUtility    文件:ConfigurationController.java   
/**
 * Constructor that optionally loads the XML file.
 */
public ConfigurationController(boolean shouldLoadXML) {
    if (shouldLoadXML) {
        this.configurationPath = this.prefs.get("configurationPath", "Path to file '/Users/user/desktop/config.xml'");
        if (isCustomConfigurationPath() && canGetFile()) {
            try {
                SAXBuilder builder = new SAXBuilder();
                File xmlFile = new File(this.configurationPath);
                Document document = builder.build(xmlFile);
                this.root = document.getRootElement();
            } catch (Exception e) {
                LOGGER.error("", e);
            }
        }
    }
}
项目:HealthCheckUtility    文件:HealthCheck.java   
/**
 * Method that counts the elements in a JSS and writes to the JSON string.
 */
public void parseObjectCount(String Object, String url, String username, String password, JSONBuilder jsonString){
    try {
        HTTPController api = new HTTPController(username, password);
        SAXBuilder sb = new SAXBuilder();
        String result = api.doGet(url + "/JSSResource/" + Object);
        Document doc = sb.build(new ByteArrayInputStream(result.getBytes("UTF-8")));
        List<Element> objects = doc.getRootElement().getChildren();
        int count = parseMultipleObjects(objects).size();

        jsonString.addObject(Object);
        jsonString.addFinalElement("count",Integer.toString(count));
        jsonString.closeObject();
    } catch (Exception e){
        e.printStackTrace();
        System.out.print(e);
    }

}
项目:mycore    文件:MCRTransferPackageUtil.java   
/**
 * Same as {@link #importObject(Path, String)} but returns a list of derivates which
 * should be imported afterwards.
 * 
 * @param targetDirectory
 *                the directory where the *.tar was unpacked
 * @param objectId
 *                object id to import
 * @throws JDOMException
 *                coulnd't parse the import order xml
 * @throws IOException
 *                when an I/O error prevents a document from being fully parsed
 * @throws MCRActiveLinkException
 *                if object is created (no real update), see {@link MCRMetadataManager#create(MCRObject)}
 * @throws MCRAccessException 
 *                if write permission is missing or see {@link MCRMetadataManager#create(MCRObject)}
 */
public static List<String> importObjectCLI(Path targetDirectory, String objectId)
    throws JDOMException, IOException, MCRActiveLinkException, MCRAccessException {
    SAXBuilder sax = new SAXBuilder();
    Path targetXML = targetDirectory.resolve(CONTENT_DIRECTORY).resolve(objectId + ".xml");
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug(MessageFormat.format("Importing {0}", targetXML.toAbsolutePath().toString()));
    }
    Document objXML = sax.build(targetXML.toFile());
    MCRObject mcr = new MCRObject(objXML);
    mcr.setImportMode(true);

    List<String> derivates = new LinkedList<>();
    // one must copy the ids before updating the mcr objects
    for (MCRMetaLinkID id : mcr.getStructure().getDerivates()) {
        derivates.add(id.getXLinkHref());
    }
    // delete children & derivate -> will be added later
    mcr.getStructure().clearChildren();
    mcr.getStructure().clearDerivates();
    // update
    MCRMetadataManager.update(mcr);
    // return list of derivates
    return derivates;
}
项目:mycore    文件:MCRSolrAltoExtractor.java   
@Override
public void accumulate(SolrInputDocument document, Path filePath, BasicFileAttributes attributes)
    throws IOException {
    String parentPath = MCRPath.toMCRPath(filePath).getParent().getOwnerRelativePath();
    if (!"/alto".equals(parentPath)) {
        return;
    }
    try (InputStream is = Files.newInputStream(filePath)) {
        SAXBuilder builder = new SAXBuilder();
        Document altoDocument = builder.build(is);
        Element rootElement = altoDocument.getRootElement();
        extractWords(rootElement).forEach(value -> document.addField("alto_words", value));
        document.addField("alto_content", extractContent(rootElement));
    } catch (JDOMException e) {
        LogManager.getLogger().error("Unable to parse {}", filePath, e);
    }
}
项目:mycore    文件:JSONSectionProviderTest.java   
@Test
public void toJSON() throws Exception {
    Map<String, String> properties = new HashMap<>();
    properties.put("MCR.WCMS2.mycoreTagList", "");
    MCRConfiguration.instance().initialize(properties, true);
    SAXBuilder builder = new SAXBuilder();
    Document doc = builder.build(new File("src/test/resources/navigation/content.xml"));
    MCRWCMSDefaultSectionProvider prov = new MCRWCMSDefaultSectionProvider();
    JsonArray sectionArray = prov.toJSON(doc.getRootElement());

    assertEquals(2, sectionArray.size());
    // test section one
    JsonObject section1 = (JsonObject) sectionArray.get(0);
    assertEquals("Title one", section1.getAsJsonPrimitive("title").getAsString());
    assertEquals("de", section1.getAsJsonPrimitive("lang").getAsString());
    assertEquals("<div><p>Content one</p><br /></div>", section1.getAsJsonPrimitive("data").getAsString());
    // test section two
    JsonObject section2 = (JsonObject) sectionArray.get(1);
    assertEquals("Title two", section2.getAsJsonPrimitive("title").getAsString());
    assertEquals("en", section2.getAsJsonPrimitive("lang").getAsString());
    assertEquals("Content two", section2.getAsJsonPrimitive("data").getAsString());
}
项目:mycore    文件:MCRAclEditorResource.java   
protected InputStream transform(String xmlFile) throws Exception {
    InputStream guiXML = getClass().getResourceAsStream(xmlFile);
    if (guiXML == null) {
        throw new WebApplicationException(Response.status(Status.INTERNAL_SERVER_ERROR).build());
    }
    SAXBuilder saxBuilder = new SAXBuilder();
    Document webPage = saxBuilder.build(guiXML);
    XPathExpression<Object> xpath = XPathFactory.instance().compile(
        "/MyCoReWebPage/section/div[@id='mycore-acl-editor2']");
    Object node = xpath.evaluateFirst(webPage);
    MCRSession mcrSession = MCRSessionMgr.getCurrentSession();
    String lang = mcrSession.getCurrentLanguage();
    if (node != null) {
        Element mainDiv = (Element) node;
        mainDiv.setAttribute("lang", lang);
        String bsPath = CONFIG.getString("MCR.bootstrap.path", "");
        if (!bsPath.equals("")) {
            bsPath = MCRFrontendUtil.getBaseURL() + bsPath;
            Element item = new Element("link").setAttribute("href", bsPath).setAttribute("rel", "stylesheet")
                .setAttribute("type", "text/css");
            mainDiv.addContent(0, item);
        }
    }
    MCRContent content = MCRJerseyUtil.transform(webPage, request);
    return content.getInputStream();
}
项目:mycore    文件:MyCoReWebPageProvider.java   
/**
 * Adds a section to the MyCoRe webpage.
 * 
 * @param title the title of the section
 * @param xmlAsString xml string which is added to the section
 * @param lang the language of the section specified by a language key.
 * @return added section
 */
public Element addSection(String title, String xmlAsString, String lang) throws IOException, SAXParseException,
    JDOMException {
    String sb = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
        + "<!DOCTYPE MyCoReWebPage PUBLIC \"-//MYCORE//DTD MYCOREWEBPAGE 1.0//DE\" "
        + "\"http://www.mycore.org/mycorewebpage.dtd\">" + "<MyCoReWebPage>" + xmlAsString + "</MyCoReWebPage>";
    SAXBuilder saxBuilder = new SAXBuilder();
    saxBuilder.setEntityResolver((publicId, systemId) -> {
        String resource = systemId.substring(systemId.lastIndexOf("/"));
        InputStream is = getClass().getResourceAsStream(resource);
        if (is == null) {
            throw new IOException(new FileNotFoundException("Unable to locate resource " + resource));
        }
        return new InputSource(is);
    });
    StringReader reader = new StringReader(sb);
    Document doc = saxBuilder.build(reader);
    return this.addSection(title, doc.getRootElement().cloneContent(), lang);
}
项目:mycore    文件:MCRDynamicURIResolver.java   
protected Element getRootElement() {
    if (cachedElement == null || xmlFile.lastModified() > lastModified) {
        try {
            SAXBuilder builder = new SAXBuilder();
            Document doc = builder.build(xmlFile);
            cachedElement = doc.getRootElement();
            lastModified = System.currentTimeMillis();
        } catch (Exception exc) {
            LOGGER.error("Error while parsing {}!", xmlFile, exc);
            return null;
        }
    }
    // clone it for further replacements
    // TODO: whats faster? cloning or building it new from file
    return cachedElement.clone();
}
项目:mycore    文件:MCRXMLHelperTest.java   
@Test
public void testList() throws Exception {
    Element child1 = new Element("child").setText("Hallo Welt");
    Element child2 = new Element("child").setText("hello world");
    Element child3 = new Element("child").setText("Bonjour le monde");
    List<Content> l1 = new ArrayList<>();
    l1.add(child1);
    l1.add(child2);
    l1.add(child3);
    Element root = new Element("root");
    root.addContent(l1);

    String formattedXML = "<root>\n<child>Hallo Welt</child>\n" + "<child>hello world</child>"
        + "<child>Bonjour le monde</child>\n</root>";
    SAXBuilder b = new SAXBuilder();
    Document doc = b.build(new ByteArrayInputStream(formattedXML.getBytes(Charset.forName("UTF-8"))));

    assertEquals("Elements should be equal", true, MCRXMLHelper.deepEqual(root, doc.getRootElement()));
}
项目:mycore    文件:MCRXMLHelperTest.java   
@Test
public void jsonSerialize() throws Exception {
    // simple text
    Element e = new Element("hallo").setText("Hallo Welt");
    JsonObject json = MCRXMLHelper.jsonSerialize(e);
    assertEquals("Hallo Welt", json.getAsJsonPrimitive("$text").getAsString());
    // attribute
    e = new Element("hallo").setAttribute("hallo", "welt");
    json = MCRXMLHelper.jsonSerialize(e);
    assertEquals("welt", json.getAsJsonPrimitive("_hallo").getAsString());

    // complex world class test
    URL world = MCRXMLHelperTest.class.getResource("/worldclass.xml");
    SAXBuilder builder = new SAXBuilder();
    Document worldDocument = builder.build(world.openStream());
    json = MCRXMLHelper.jsonSerialize(worldDocument.getRootElement());
    assertNotNull(json);
    assertEquals("World", json.getAsJsonPrimitive("_ID").getAsString());
    assertEquals("http://www.w3.org/2001/XMLSchema-instance", json.getAsJsonPrimitive("_xmlns:xsi").getAsString());
    JsonObject deLabel = json.getAsJsonArray("label").get(0).getAsJsonObject();
    assertEquals("de", deLabel.getAsJsonPrimitive("_xml:lang").getAsString());
    assertEquals("Staaten", deLabel.getAsJsonPrimitive("_text").getAsString());
    assertEquals(2, json.getAsJsonObject("categories").getAsJsonArray("category").size());
}
项目:mycore    文件:MCRCategoryJsonTest.java   
@Test
public void deserialize() throws Exception {
    MCRConfiguration mcrProperties = MCRConfiguration.instance();
    mcrProperties.initialize(MCRConfigurationLoaderFactory.getConfigurationLoader().load(), true);
    mcrProperties.set("MCR.Metadata.DefaultLang", "de");
    mcrProperties.set("MCR.Category.DAO", CategoryDAOMock.class.getName());

    SAXBuilder saxBuilder = new SAXBuilder();
    Document doc = saxBuilder.build(getClass().getResourceAsStream("/classi/categoryJsonErr.xml"));
    String json = doc.getRootElement().getText();

    Gson gson = MCRJSONManager.instance().createGson();
    try {
        MCRCategoryImpl fromJson = gson.fromJson(json, MCRCategoryImpl.class);
        System.out.println("FOO");
    } catch (Exception e) {
        e.printStackTrace();
    }
}
项目:OnlineShoppingSystem    文件:DBConfig.java   
/**
 * 在初始化时从文件中获取配置并保存
 */
public DBConfig() {
    SAXBuilder jdomBuilder = new SAXBuilder();

    try {
        String configPath = DBConfig.class.getResource("/")
                + "../../config/database-config.xml";

        Document document = jdomBuilder.build(configPath);

        Element root = document.getRootElement();

        setDriver(root.getChildText("driver").trim());
        setHost(root.getChildText("host").trim());
        setPort(root.getChildText("port").trim());
        setUsername(root.getChildText("username").trim());
        setPassword(root.getChildText("password").trim());
        setName(root.getChildText("name").trim());
    } catch (JDOMException | IOException e) {
        e.printStackTrace();
    }
}
项目:dgm    文件:JoyMenuTag.java   
/**
 * Create a top menu
 * @param out write output
 * @throws IOException 
 */
private void leftMenu(JspWriter out) throws IOException {         
    try {
        SAXBuilder sxb = new SAXBuilder();
        org.jdom2.Document document;
        Element racine;
        String sMenu ="";
        String xmlConfigFile = (xmlConfig.equals("") ? "joy-menu.xml" : xmlConfig);

        document = sxb.build(Thread.currentThread().getContextClassLoader().getResourceAsStream(xmlConfigFile));
        racine = document.getRootElement();
        List root = racine.getChildren("joy-menu");
        sMenu = buildLeftMenuBloc(root, sMenu);

        out.println("<div id='" + cssDivMenu + "'>");

        out.println(sMenu);
        out.println("</div>");
        menuCache = sMenu;

    } catch (IOException | JDOMException ex) {
        Joy.log().debug ( ex.toString());
        out.println("No menu defined.");
    }
}
项目:Arcade2    文件:XMLPreProcessor.java   
@Override
public Element process(ArcadePlugin plugin, Element element, String path) throws Throwable {
    File file = new File(path);
    if (file.exists()) {
        SAXBuilder builder = new SAXBuilder();
        Element root = builder.build(file).getRootElement();

        if (root != null) {
            XMLPreProcessor handler = new XMLPreProcessor(plugin, root);
            handler.prepare();

            handler.run();
            return handler.getElement();
        }
    }

    return null;
}
项目:mealOrdering    文件:DBConfig.java   
/**
 * 鍦ㄥ垵濮嬪寲鏃朵粠鏂囦欢涓幏鍙栭厤缃苟淇濆瓨
 */
public DBConfig() {
    SAXBuilder jdomBuilder = new SAXBuilder();

    try {
        String configPath = DBConfig.class.getResource("/") + "../../config/mysql.xml";

        Document document = jdomBuilder.build(configPath);

        Element root = document.getRootElement();

        setHost(root.getChildText("host").trim());
        setPort(root.getChildText("port").trim());
        setDatabase(root.getChildText("database").trim());
        setUsername(root.getChildText("username").trim());
        setPassword(root.getChildText("password").trim());
    } catch (JDOMException | IOException e) {
        e.printStackTrace();
    }
}
项目:bbb-resources    文件:LoginBean.java   
public ArrayList<User> getUsersFromXML () throws JDOMException, IOException {
  ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
  ArrayList<User> users = new ArrayList<User>();
  SAXBuilder saxBuilder = new SAXBuilder();

  File inputFile = new File(ec.getRealPath("/") + "WEB-INF\\users.xml");
  Document document = saxBuilder.build(inputFile);
  Element root = document.getRootElement();
  List<Element> usersList = root.getChildren();

  for (Element user : usersList) {
    users.add(new User(
      Integer.valueOf(user.getChild("id").getText()),
      user.getChild("username").getText(),
      user.getChild("password").getText()
    ));
  }

  return users;
}
项目:bbb-resources    文件:RootBean.java   
public List<Product> getProductsFromXML () throws JDOMException, IOException {
  ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
  List<Product> products = new ArrayList<Product>();
  SAXBuilder saxBuilder = new SAXBuilder();

  File inputFile = new File(ec.getRealPath("/") + "WEB-INF\\products.xml");
  Document document = saxBuilder.build(inputFile);
  Element root = document.getRootElement();
  List<Element> productsList = root.getChildren();

  for (Element product : productsList) {
    products.add(new Product(
      product.getChild("name").getText(),
      product.getChild("link").getText(),
      product.getChild("description").getText()
    ));
  }

  return products;
}
项目:bbb-resources    文件:GuestBookBean.java   
private ArrayList<Entry> getEntriesFromXML () throws JDOMException, IOException, ParseException {
  ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
  ArrayList<Entry> entries = new ArrayList<Entry>();
  SAXBuilder saxBuilder = new SAXBuilder();

  File inputFile = new File(ec.getRealPath("/") + "WEB-INF\\entries.xml");
  Document document = saxBuilder.build(inputFile);
  Element root = document.getRootElement();
  List<Element> children = root.getChildren();

  for (Element entry : children) {
    entries.add(new Entry(
      Integer.valueOf(entry.getChild("id").getText()),
      entry.getChild("title").getText(),
      Date.from(Instant.parse(entry.getChild("createdAt").getText())),
      entry.getChild("message").getText()
    ));
  }

  return entries;
}
项目:bbb-resources    文件:LoginBean.java   
public ArrayList<User> getUsersFromXML () throws JDOMException, IOException {
  ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
  ArrayList<User> users = new ArrayList<User>();
  SAXBuilder saxBuilder = new SAXBuilder();

  File inputFile = new File(ec.getRealPath("/") + "WEB-INF\\users.xml");
  Document document = saxBuilder.build(inputFile);
  Element root = document.getRootElement();
  List<Element> usersList = root.getChildren();

  for (Element user : usersList) {
    users.add(new User(
      Integer.valueOf(user.getChild("id").getText()),
      user.getChild("username").getText(),
      user.getChild("password").getText()
    ));
  }

  return users;
}
项目:personal    文件:JDomTest.java   
public static void main(String[] args) throws Exception{
    SAXBuilder saxBuilder = new SAXBuilder();
    Document document = saxBuilder.build(JDomTest.class.getClassLoader().getResourceAsStream("test.xml"));
    Element root = document.getRootElement();
    List elementList = root.getChildren("department");

    for (int i = 0; i < elementList.size(); i++) {
        Element element = (Element)elementList.get(i);
        String elementName = element.getAttributeValue("name");
        System.out.println("Department: " + elementName);
        String unit = element.getChildText("unit");
        System.out.println("Unit: " + unit);
        List courseList = element.getChildren("course");
        for (int j = 0; j < courseList.size(); j++) {
            Element course = (Element)courseList.get(j);
            System.out.println("Class: " + course.getText().trim());
        }
    }
}
项目:ldapchai    文件:DirXMLEntitlementRef.java   
private static Document convertStrToDoc( final String str )
{
    final Reader xmlreader = new StringReader( str );
    final SAXBuilder builder = new SAXBuilder();
    Document doc = null;
    try
    {
        doc = builder.build( xmlreader );
    }
    catch ( JDOMException | IOException e )
    {
        //@todo
        e.printStackTrace();
    }
    return doc;
}
项目:Overcast-Livestreamer-Mod    文件:RenderListener.java   
@SubscribeEvent
public void messageReceived(ClientChatReceivedEvent event) {
    try {
        String message = event.getMessage().getFormattedText();
        if (message.contains("XML")) {
            String str = message.replaceAll("�", "");
            str = str.substring(str.indexOf("https"), str.length() - 2);
            SAXBuilder builder = new SAXBuilder();
            InputStream input = new URL(str).openStream();
            org.jdom2.Document document = builder.build(input);
            this.document = document;
            FileUtil.stringToFile("Unknown Name", StreamerMod.mapNameFile.getAbsolutePath());
            for (Element element : document.getRootElement().getChildren("name")) {
                FileUtil.stringToFile(element.getValue(), StreamerMod.mapNameFile.getAbsolutePath());
            }
            ModRenderer.playerTeams.clear();
            ModRenderer.playerNameTeams.clear();
            ModRenderer.deadPlayers.clear();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
项目:maker    文件:MessageUtil.java   
/**
 * 解析微信发来的请求(XML)
 * 
 * @param xml
 * @return
 * @throws Exception
 */
public static Map<String, String> parseXml(HttpServletRequest request) throws Exception {
    SAXBuilder builder = new SAXBuilder();
    Document document = builder.build(request.getInputStream());
    // 将解析结果存储在HashMap中
    Map<String, String> map = new HashMap<String, String>();
    // 得到xml根元素
    Element root = document.getRootElement();
    // 得到根元素的所有子节点
    List<Element> elementList = root.getChildren();

    // 遍历所有子节点
    for (Element e : elementList)
        map.put(e.getName(), e.getText());
    return map;
}
项目:DeadReckoning    文件:CarPark.java   
public CarPark(String filename) {

        Document doc = null;
        SAXBuilder builder = new SAXBuilder();
        try {
            doc = (Document) builder.build(filename);
        } catch (JDOMException | IOException e) {
            e.printStackTrace();
        }

        name = getName(doc);
        boundary = getBBox(doc);
        Map<Integer, GeoNode> nodes = getNodes(doc);
        Map<Integer, Way> ways = getWays(doc, nodes);
        List<Storey> storeies = getStoreies(doc, ways);
        calibBoxes = getCalibBoxes(doc, nodes);
        addAll(storeies);
        Collections.sort(this, Collections.reverseOrder());
    }
项目:DeadReckoning    文件:Reader.java   
public Reader(File file, String name) {
    SAXBuilder builder = new SAXBuilder();
    try {

        doc = (Document) builder.build(file);
        Element root = doc.getRootElement();

        // use the default implementation
        XPathFactory xFactory = XPathFactory.instance();
        // System.out.println(xFactory.getClass());

        // select all data for motion sensor
        XPathExpression<Element> expr = xFactory.compile(
                "/SensorData/data[@" + Data.NAMETAG + "='" + name + "']",
                Filters.element());

        it = expr.evaluate(doc).iterator();

    } catch (IOException io) {
        System.out.println(io.getMessage());
    } catch (JDOMException jdomex) {
        System.out.println(jdomex.getMessage());
    }
}
项目:DeadReckoning    文件:Reader.java   
public Reader(File file) {
    SAXBuilder builder = new SAXBuilder();
    try {

        doc = (Document) builder.build(file);
        Element root = doc.getRootElement();

        // use the default implementation
        XPathFactory xFactory = XPathFactory.instance();
        // System.out.println(xFactory.getClass());

        // select all data for motion sensor
        XPathExpression<Element> expr = xFactory.compile(
                "/SensorData/data", Filters.element());

        it = expr.evaluate(doc).iterator();

    } catch (IOException io) {
        System.out.println(io.getMessage());
    } catch (JDOMException jdomex) {
        System.out.println(jdomex.getMessage());
    }
}
项目:agui_framework    文件:AnimationUtils.java   
/**
   * Loads an {@link Animation} object from a resource
   *
   * @param context Application context used to access resources
   * @param id The resource id of the animation to load
   * @return The animation object reference by the specified id
   * @throws NotFoundException when the animation cannot be loaded
   */
  public static Animation loadAnimation(Context context, int id) {
    try {
    Animation anim = null;
    String path = context.getResources().getAnimation(id);
    if(path != null) {
        InputStream is = MyUtils.getResourceInputStream(path);
        if(is != null) {
            // FIXME : 매번 이렇게 animation 실행마다 파일을 읽어와서 하는 것은 performance를 많이 떨어트린다.
            BufferedInputStream bi = new BufferedInputStream(is);//in);
            Element root = new SAXBuilder().build(bi).getRootElement();
            String type = root.getName();

            AttributeSet attrs = new AttributeSet(context, root);
            anim = createAnimationFromXml(context, type, null, attrs, root);

            bi.close();
        }
    }
    return anim;
    } catch (Exception e) {
        e.printStackTrace();
    }
throw new NotFoundException();
  }
项目:informa    文件:FeedParser.java   
/**
 * Parse feed from input source with base location set and create channel.
 *
 * @param cBuilder     specific channel builder to use.
 * @param inpSource    input source of data.
 * @param baseLocation base location of feed.
 * @return parsed channel.
 * @throws IOException    if IO errors occur.
 * @throws ParseException if parsing is not possible.
 */
public static ChannelIF parse(ChannelBuilderIF cBuilder, InputSource inpSource,
                              URL baseLocation)
        throws IOException, ParseException {
    // document reading without validation
    SAXBuilder saxBuilder = new SAXBuilder();

    // turn off DTD loading
    saxBuilder.setEntityResolver(new NoOpEntityResolver());

    try {
        Document doc = saxBuilder.build(inpSource);
        ChannelIF channel = parse(cBuilder, doc);
        channel.setLocation(baseLocation);
        return channel;
    } catch (JDOMException e) {
        throw new ParseException("Problem parsing " + inpSource + ": " + e);
    }
}
项目:ml-app-deployer    文件:Fragment.java   
public Fragment(String xml, Namespace... namespaces) {
     try {
         internalDoc = new SAXBuilder().build(new StringReader(xml));
         List<Namespace> list = new ArrayList<Namespace>();
         list.add(Namespace.getNamespace("c", "http://marklogic.com/manage/clusters"));
         list.add(Namespace.getNamespace("db", "http://marklogic.com/manage/databases"));
         list.add(Namespace.getNamespace("es", "http://marklogic.com/entity-services"));
         list.add(Namespace.getNamespace("f", "http://marklogic.com/manage/forests"));
      list.add(Namespace.getNamespace("g", "http://marklogic.com/manage/groups"));
      list.add(Namespace.getNamespace("h", "http://marklogic.com/manage/hosts"));
         list.add(Namespace.getNamespace("m", "http://marklogic.com/manage"));
         list.add(Namespace.getNamespace("s", "http://marklogic.com/manage/servers"));
         list.add(Namespace.getNamespace("msec", "http://marklogic.com/manage/security"));
         list.add(Namespace.getNamespace("sec", "http://marklogic.com/xdmp/security"));
         list.add(Namespace.getNamespace("arp", "http://marklogic.com/manage/alert-rule/properties"));
list.add(Namespace.getNamespace("ts", "http://marklogic.com/manage/task-server"));
list.add(Namespace.getNamespace("req", "http://marklogic.com/manage/requests"));
      list.add(Namespace.getNamespace("t", "http://marklogic.com/manage/tasks"));
         for (Namespace n : namespaces) {
             list.add(n);
         }
         this.namespaces = list.toArray(new Namespace[] {});
     } catch (Exception e) {
         throw new RuntimeException(String.format("Unable to parse XML, cause: %s; XML: %s", e.getMessage(), xml), e);
     }
 }
项目:bigwarp    文件:BigWarp.java   
protected void loadSettings( final String xmlFilename ) throws IOException,
        JDOMException
{
    final SAXBuilder sax = new SAXBuilder();
    final Document doc = sax.build( xmlFilename );
    final Element root = doc.getRootElement();
    viewerP.stateFromXml( root.getChild( "viewerP" ) );
    viewerQ.stateFromXml( root.getChild( "viewerQ" ) );
    setupAssignments.restoreFromXml( root );
    bookmarks.restoreFromXml( root );
    activeSourcesDialogP.update();
    activeSourcesDialogQ.update();

    viewerFrameP.repaint();
    viewerFrameQ.repaint();
}
项目:marklogic-spring-batch    文件:HttpXmlItemReader.java   
@Override
public void open(ExecutionContext executionContext) throws ItemStreamException {
    ResponseEntity<String> response = restTemplate.getForEntity(uri, String.class);
    if (!response.getStatusCode().equals(HttpStatus.OK)) {
        throw new ItemStreamException(response.getStatusCode() + " HTTP response is returned");
    }
    ;
    MediaType type = response.getHeaders().getContentType();
    if (MediaType.APPLICATION_XML.equals(type) ||
            MediaType.APPLICATION_ATOM_XML.equals(type) ||
            MediaType.APPLICATION_XHTML_XML.equals(type) ||
            MediaType.APPLICATION_RSS_XML.equals(type) ||
            "text/xml".equals(type.toString())) {
        SAXBuilder jdomBuilder = new SAXBuilder();
        try {
            Document document = jdomBuilder.build(new StringReader(response.getBody()));
            ElementFilter ef = new ElementFilter(aggregateRecordElement);
            aggregateRecordElementItr = document.getRootElement().getDescendants(ef);
        } catch (Exception ex) {
            throw new ItemStreamException(ex);
        }
    }
}
项目:CABSF_Java    文件:XMLUtilities.java   
/**
 * Xml string tojdom2 document.
 * 
 * @param xmlString
 *            the xml string
 * @return the org.jdom2. document
 * @throws JDOMException
 *             the JDOM exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
static public org.jdom2.Document xmlStringTojdom2Document(final String xmlString)
        throws JDOMException, IOException {
    StringReader sr = null;
    InputSource inputSource = null;
    Document document = null;

    try {
        sr = new StringReader(xmlString);
        inputSource = new InputSource(sr);

        final SAXBuilder saxBuilder = new SAXBuilder();
        // begin of try - catch block
        document = saxBuilder.build(inputSource);

        final Element root = document.getRootElement();
        System.out.println("Successfully loaded template file: " + root.getName());
    } finally {
        if (sr != null)
            sr.close();
    }

    return document;

}