List of usage examples for org.w3c.dom Node getChildNodes
public NodeList getChildNodes();
NodeList
that contains all children of this node. From source file:Main.java
public static void main(String[] argv) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(true);/*from ww w.ja v a 2 s . co m*/ factory.setExpandEntityReferences(false); Document doc1 = factory.newDocumentBuilder().parse(new File("filename")); NodeList list = doc1.getElementsByTagName("entry"); Element element = (Element) list.item(0); Document doc2 = factory.newDocumentBuilder().parse(new File("infilename2.xml")); // Make a copy of the element subtree suitable for inserting into doc2 Node node = doc2.importNode(element, true); // Get the parent Node parent = node.getParentNode(); // Get children NodeList children = node.getChildNodes(); // Get first child; null if no children Node child = node.getFirstChild(); // Get last child; null if no children child = node.getLastChild(); // Get next sibling; null if node is last child Node sibling = node.getNextSibling(); // Get previous sibling; null if node is first child sibling = node.getPreviousSibling(); // Get first sibling sibling = node.getParentNode().getFirstChild(); // Get last sibling sibling = node.getParentNode().getLastChild(); }
From source file:XMLInfo.java
public static void main(String args[]) { try {//from w w w . ja v a 2s .co m DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse("xmlFileName.xml"); Node root = document.getDocumentElement(); System.out.print("Here is the document's root node:"); System.out.println(" " + root.getNodeName()); System.out.println("Here are its child elements: "); NodeList childNodes = root.getChildNodes(); Node currentNode; for (int i = 0; i < childNodes.getLength(); i++) { currentNode = childNodes.item(i); System.out.println(currentNode.getNodeName()); } // get first child of root element currentNode = root.getFirstChild(); System.out.print("The first child of root node is: "); System.out.println(currentNode.getNodeName()); // get next sibling of first child System.out.print("whose next sibling is: "); currentNode = currentNode.getNextSibling(); System.out.println(currentNode.getNodeName()); // print value of next sibling of first child System.out.println("value of " + currentNode.getNodeName() + " element is: " + currentNode.getFirstChild().getNodeValue()); // print name of parent of next sibling of first child System.out.print("Parent node of " + currentNode.getNodeName() + " is: " + currentNode.getParentNode().getNodeName()); } // handle exception creating DocumentBuilder catch (ParserConfigurationException parserError) { System.err.println("Parser Configuration Error"); parserError.printStackTrace(); } // handle exception reading data from file catch (IOException fileException) { System.err.println("File IO Error"); fileException.printStackTrace(); } // handle exception parsing XML document catch (SAXException parseException) { System.err.println("Error Parsing Document"); parseException.printStackTrace(); } }
From source file:client.QueryLastFm.java
License:asdf
public static void main(String[] args) throws Exception { // isAlreadyInserted("asdfs","jas,jnjkah"); // FileWriter fw = new FileWriter(".\\tracks.csv"); OutputStream track_os = new FileOutputStream(".\\tracks.csv"); PrintWriter out = new PrintWriter(new OutputStreamWriter(track_os, "UTF-8")); OutputStream track_id_os = new FileOutputStream(".\\track_id_sim_track_id.csv"); PrintWriter track_id_out = new PrintWriter(new OutputStreamWriter(track_id_os, "UTF-8")); track_id_out.print(""); ByteArrayInputStream input;/*from ww w . j a v a2s .c o m*/ Document doc = null; CloseableHttpClient httpclient = HttpClients.createDefault(); String trackName = ""; String artistName = ""; String sourceMbid = ""; out.print("ID");// first row first column out.print(","); out.print("TrackName");// first row second column out.print(","); out.println("Artist");// first row third column track_id_out.print("source");// first row second column track_id_out.print(","); track_id_out.println("target");// first row third column // track_id_out.print(","); // track_id_out.println("type");// first row third column // out.flush(); // out.close(); // fw.close(); // os.close(); try { URI uri = new URIBuilder().setScheme("http").setHost("ws.audioscrobbler.com").setPath("/2.0/") .setParameter("method", "track.getsimilar").setParameter("artist", "cher") .setParameter("track", "believe").setParameter("limit", "100") .setParameter("api_key", "88858618961414f8bec919bddd057044").build(); // new URIBuilder(). HttpGet request = new HttpGet(uri); // request. // This is useful for last.fm logging and preventing them from blocking this client request.setHeader(HttpHeaders.USER_AGENT, "nileshmore@gatech.edu - ClassAssignment at GeorgiaTech Non-commercial use"); HttpGet httpGet = new HttpGet( "http://ws.audioscrobbler.com/2.0/?method=track.getsimilar&artist=cher&track=believe&limit=4&api_key=88858618961414f8bec919bddd057044"); CloseableHttpResponse response = httpclient.execute(request); int statusCode = response.getStatusLine().getStatusCode(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); // The underlying HTTP connection is still held by the response object // to allow the response content to be streamed directly from the network socket. // In order to ensure correct deallocation of system resources // the user MUST call CloseableHttpResponse#close() from a finally clause. // Please note that if response content is not fully consumed the underlying // connection cannot be safely re-used and will be shut down and discarded // by the connection manager. try { if (statusCode == 200) { HttpEntity entity1 = response.getEntity(); BufferedReader br = new BufferedReader( new InputStreamReader((response.getEntity().getContent()))); Document document = builder.parse((response.getEntity().getContent())); Element root = document.getDocumentElement(); root.normalize(); // Need to focus and resolve this part NodeList nodes; nodes = root.getChildNodes(); nodes = root.getElementsByTagName("track"); if (nodes.getLength() == 0) { // System.out.println("empty"); return; } Node trackNode; for (int k = 0; k < nodes.getLength(); k++) // can access all tracks now { trackNode = nodes.item(k); NodeList trackAttributes = trackNode.getChildNodes(); // check if mbid is present in track attributes // System.out.println("Length " + (trackAttributes.item(5).getNodeName().compareToIgnoreCase("mbid") == 0)); if ((trackAttributes.item(5).getNodeName().compareToIgnoreCase("mbid") == 0)) { if (((Element) trackAttributes.item(5)).hasChildNodes()) ;// System.out.println("Go aHead"); else continue; } else continue; for (int n = 0; n < trackAttributes.getLength(); n++) { Node attribute = trackAttributes.item(n); if ((attribute.getNodeName().compareToIgnoreCase("name")) == 0) { // System.out.println(((Element)attribute).getFirstChild().getNodeValue()); trackName = ((Element) attribute).getFirstChild().getNodeValue(); // make string encoding as UTF-8 ************ } if ((attribute.getNodeName().compareToIgnoreCase("mbid")) == 0) { // System.out.println(n + " " + ((Element)attribute).getFirstChild().getNodeValue()); sourceMbid = attribute.getFirstChild().getNodeValue(); } if ((attribute.getNodeName().compareToIgnoreCase("artist")) == 0) { NodeList ArtistNodeList = attribute.getChildNodes(); for (int j = 0; j < ArtistNodeList.getLength(); j++) { Node Artistnode = ArtistNodeList.item(j); if ((Artistnode.getNodeName().compareToIgnoreCase("name")) == 0) { // System.out.println(((Element)Artistnode).getFirstChild().getNodeValue()); artistName = ((Element) Artistnode).getFirstChild().getNodeValue(); } } } } out.print(sourceMbid); out.print(","); out.print(trackName); out.print(","); out.println(artistName); // out.print(","); findSimilarTracks(track_id_out, sourceMbid, trackName, artistName); } track_id_out.flush(); out.flush(); out.close(); track_id_out.close(); track_os.close(); // fw.close(); Element trac = (Element) nodes.item(0); // trac.normalize(); nodes = trac.getChildNodes(); // System.out.println(nodes.getLength()); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); // System.out.println(node.getNodeName()); if ((node.getNodeName().compareToIgnoreCase("name")) == 0) { // System.out.println(((Element)node).getFirstChild().getNodeValue()); } if ((node.getNodeName().compareToIgnoreCase("mbid")) == 0) { // System.out.println(((Element)node).getFirstChild().getNodeValue()); } if ((node.getNodeName().compareToIgnoreCase("artist")) == 0) { // System.out.println("Well"); NodeList ArtistNodeList = node.getChildNodes(); for (int j = 0; j < ArtistNodeList.getLength(); j++) { Node Artistnode = ArtistNodeList.item(j); if ((Artistnode.getNodeName().compareToIgnoreCase("name")) == 0) { /* System.out.println(((Element)Artistnode).getFirstChild().getNodeValue());*/ } /*System.out.println(Artistnode.getNodeName());*/ } } } /*if(node instanceof Element){ //a child element to process Element child = (Element) node; String attribute = child.getAttribute("width"); }*/ // System.out.println(root.getAttribute("status")); NodeList tracks = root.getElementsByTagName("track"); Element track = (Element) tracks.item(0); // System.out.println(track.getTagName()); track.getChildNodes(); } else { System.out.println("failed with status" + response.getStatusLine()); } // input = (ByteArrayInputStream)entity1.getContent(); // do something useful with the response body // and ensure it is fully consumed } finally { response.close(); } } finally { System.out.println("Exited succesfully."); httpclient.close(); } }
From source file:AndroidUninstallStock.java
@SuppressWarnings("static-access") public static void main(String[] args) { try {//from w ww. j av a 2s . c o m String lang = Locale.getDefault().getLanguage(); GnuParser cmdparser = new GnuParser(); Options cmdopts = new Options(); for (String fld : Arrays.asList("shortOpts", "longOpts", "optionGroups")) { // hack for printOptions java.lang.reflect.Field fieldopt = cmdopts.getClass().getDeclaredField(fld); fieldopt.setAccessible(true); fieldopt.set(cmdopts, new LinkedHashMap<>()); } cmdopts.addOption("h", "help", false, "Help"); cmdopts.addOption("t", "test", false, "Show only report"); cmdopts.addOption(OptionBuilder.withLongOpt("adb").withArgName("file").hasArg() .withDescription("Path to ADB from Android SDK").create("a")); cmdopts.addOption(OptionBuilder.withLongOpt("dev").withArgName("device").hasArg() .withDescription("Select device (\"adb devices\")").create("d")); cmdopts.addOption(null, "restore", false, "If packages have not yet removed and are disabled, " + "you can activate them again"); cmdopts.addOption(null, "google", false, "Delete packages are in the Google section"); cmdopts.addOption(null, "unapk", false, "Delete /system/app/ *.apk *.odex *.dex" + System.lineSeparator() + "(It is required to repeat command execution)"); cmdopts.addOption(null, "unlib", false, "Delete /system/lib/[libs in apk]"); //cmdopts.addOption(null, "unfrw", false, "Delete /system/framework/ (special list)"); cmdopts.addOption(null, "scanlibs", false, "(Dangerous!) Include all the libraries of selected packages." + " Use with --unlib"); cmdopts.addOptionGroup(new OptionGroup() { { addOption(OptionBuilder.withLongOpt("genfile").withArgName("file").hasArg().isRequired() .withDescription("Create file with list packages").create()); addOption(OptionBuilder.withLongOpt("lang").withArgName("ISO 639").hasArg().create()); } }); cmdopts.getOption("lang").setDescription( "See hl= in Google URL (default: " + lang + ") " + "for description from Google Play Market"); CommandLine cmd = cmdparser.parse(cmdopts, args); if (args.length == 0 || cmd.hasOption("help")) { PrintWriter console = new PrintWriter(System.out); HelpFormatter cmdhelp = new HelpFormatter(); cmdhelp.setOptionComparator(new Comparator<Option>() { @Override public int compare(Option o1, Option o2) { return 0; } }); console.println("WARNING: Before use make a backup with ClockworkMod Recovery!"); console.println(); console.println("AndroidUninstallStock [options] [AndroidListSoft.xml]"); cmdhelp.printOptions(console, 80, cmdopts, 3, 2); console.flush(); return; } String adb = cmd.getOptionValue("adb", "adb"); try { run(adb, "start-server"); } catch (IOException e) { System.out.println("Error: Not found ADB! Use -a or --adb"); return; } final boolean NotTest = !cmd.hasOption("test"); String deverror = getDeviceStatus(adb, cmd.getOptionValue("dev")); if (!deverror.isEmpty()) { System.out.println(deverror); return; } System.out.println("Getting list packages:"); LinkedHashMap<String, String> apklist = new LinkedHashMap<String, String>(); for (String ln : run(adb, "-s", lastdevice, "shell", "pm list packages -s -f")) { // "pm list packages" give list sorted by packages ;) String pckg = ln.substring("package:".length()); String pckgname = ln.substring(ln.lastIndexOf('=') + 1); pckg = pckg.substring(0, pckg.length() - pckgname.length() - 1); if (!pckgname.equals("android") && !pckgname.equals("com.android.vending")/*Google Play Market*/) { apklist.put(pckg, pckgname); } } for (String ln : run(adb, "-s", lastdevice, "shell", "ls /system/app/")) { String path = "/system/app/" + ln.replace(".odex", ".apk").replace(".dex", ".apk"); if (!apklist.containsKey(path)) { apklist.put(path, ""); } } apklist.remove("/system/app/mcRegistry"); for (Map.Entry<String, String> info : sortByValues(apklist).entrySet()) { System.out.println(info.getValue() + " = " + info.getKey()); } String genfile = cmd.getOptionValue("genfile"); if (genfile != null) { Path genpath = Paths.get(genfile); try (BufferedWriter gen = Files.newBufferedWriter(genpath, StandardCharsets.UTF_8, new StandardOpenOption[] { StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE })) { if (cmd.getOptionValue("lang") != null) { lang = cmd.getOptionValue("lang"); } LinkedHashSet<String> listsystem = new LinkedHashSet<String>() { { add("com.android"); add("com.google.android"); //add("com.sec.android.app"); add("com.monotype.android"); add("eu.chainfire.supersu"); } }; // \r\n for Windows Notepad gen.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n"); gen.write("<!-- & raplace with & or use <![CDATA[ ]]> -->\r\n"); gen.write("<AndroidUninstallStock>\r\n\r\n"); gen.write("<Normal>\r\n"); System.out.println(); System.out.println("\tNormal:"); writeInfo(gen, apklist, lang, listsystem, true); gen.write("\t<apk name=\"Exclude Google and etc\">\r\n"); for (String exc : listsystem) { gen.write("\t\t<exclude global=\"true\" in=\"package\" pattern=\"" + exc + "\" />\r\n"); } gen.write("\t</apk>\r\n"); gen.write("</Normal>\r\n\r\n"); gen.write("<Google>\r\n"); System.out.println(); System.out.println("\tGoogle:"); writeInfo(gen, apklist, lang, listsystem, false); gen.write("</Google>\r\n\r\n"); gen.write("</AndroidUninstallStock>\r\n"); System.out.println("File " + genpath.toAbsolutePath() + " created."); } return; } String[] FileName = cmd.getArgs(); if (!(FileName.length > 0 && Files.isReadable(Paths.get(FileName[0])))) { System.out.println("Error: File " + FileName[0] + " not found!"); return; } DocumentBuilderFactory xmlfactory = getXmlDocFactory(); // DocumentBuilder.setErrorHandler() for print errors Document xml = xmlfactory.newDocumentBuilder().parse(new File(FileName[0])); LinkedList<AusInfo> Normal = new LinkedList<AusInfo>(); LinkedList<AusInfo> Google = new LinkedList<AusInfo>(); NodeList ndaus = xml.getElementsByTagName("AndroidUninstallStock").item(0).getChildNodes(); for (int ndausx = 0, ndausc = ndaus.getLength(); ndausx < ndausc; ndausx++) { Node ndnow = ndaus.item(ndausx); NodeList nd = ndnow.getChildNodes(); String ndname = ndnow.getNodeName(); for (int ndx = 0, ndc = nd.getLength(); ndx < ndc; ndx++) { if (!nd.item(ndx).getNodeName().equalsIgnoreCase("apk")) { continue; } if (ndname.equalsIgnoreCase("Normal")) { Normal.add(getApkInfo(nd.item(ndx))); } else if (ndname.equalsIgnoreCase("Google")) { Google.add(getApkInfo(nd.item(ndx))); } } } // FIXME This part must be repeated until the "pm uninstall" will not issue "Failure" on all packages. // Now requires a restart. System.out.println(); System.out.println("Include and Exclude packages (Normal):"); LinkedHashMap<String, String> apkNormal = getApkFromPattern(apklist, Normal, false); System.out.println(); System.out.println("Global Exclude packages (Normal):"); apkNormal = getApkFromPattern(apkNormal, Normal, true); System.out.println(); System.out.println("Final list packages (Normal):"); for (Map.Entry<String, String> info : sortByValues(apkNormal).entrySet()) { System.out.println(info.getValue() + " = " + info.getKey()); } LinkedHashMap<String, String> apkGoogle = new LinkedHashMap<String, String>(); if (cmd.hasOption("google")) { System.out.println(); System.out.println("Include and Exclude packages (Google):"); apkGoogle = getApkFromPattern(apklist, Google, false); System.out.println(); System.out.println("Global Exclude packages (Google):"); apkGoogle = getApkFromPattern(apkGoogle, Google, true); System.out.println(); System.out.println("Final list packages (Google):"); for (Map.Entry<String, String> info : sortByValues(apkGoogle).entrySet()) { System.out.println(info.getValue() + " = " + info.getKey()); } } if (NotTest) { if (!hasRoot(adb)) { System.out.println("No Root"); System.out.println(); System.out.println("FINISH :)"); return; } } if (cmd.hasOption("restore")) { System.out.println(); System.out.println("Enable (Restore) packages (Normal):"); damage(adb, "pm enable ", NotTest, apkNormal, 2); if (cmd.hasOption("google")) { System.out.println(); System.out.println("Enable (Restore) packages (Google):"); damage(adb, "pm enable ", NotTest, apkGoogle, 2); } System.out.println(); System.out.println("FINISH :)"); return; } else { System.out.println(); System.out.println("Disable packages (Normal):"); damage(adb, "pm disable ", NotTest, apkNormal, 2); if (cmd.hasOption("google")) { System.out.println(); System.out.println("Disable packages (Google):"); damage(adb, "pm disable ", NotTest, apkGoogle, 2); } } if (!cmd.hasOption("unapk") && !cmd.hasOption("unlib")) { System.out.println(); System.out.println("FINISH :)"); return; } // Reboot now not needed /*if (NotTest) { reboot(adb, "-s", lastdevice, "reboot"); if (!hasRoot(adb)) { System.out.println("No Root"); System.out.println(); System.out.println("FINISH :)"); return; } }*/ if (cmd.hasOption("unlib")) { // "find" not found System.out.println(); System.out.println("Getting list libraries:"); LinkedList<String> liblist = new LinkedList<String>(); liblist.addAll(run(adb, "-s", lastdevice, "shell", "ls -l /system/lib/")); String dircur = "/system/lib/"; for (int x = 0; x < liblist.size(); x++) { if (liblist.get(x).startsWith("scan:")) { dircur = liblist.get(x).substring("scan:".length()); liblist.remove(x); x--; } else if (liblist.get(x).startsWith("d")) { String dir = liblist.get(x).substring(liblist.get(x).lastIndexOf(':') + 4) + "/"; liblist.remove(x); x--; liblist.add("scan:/system/lib/" + dir); liblist.addAll(run(adb, "-s", lastdevice, "shell", "ls -l /system/lib/" + dir)); continue; } liblist.set(x, dircur + liblist.get(x).substring(liblist.get(x).lastIndexOf(':') + 4)); System.out.println(liblist.get(x)); } final boolean scanlibs = cmd.hasOption("scanlibs"); LinkedHashMap<String, String> libNormal = getLibFromPatternInclude(adb, liblist, apkNormal, Normal, "Normal", scanlibs); libNormal = getLibFromPatternGlobalExclude(libNormal, Normal, "Normal"); System.out.println(); System.out.println("Final list libraries (Normal):"); for (Map.Entry<String, String> info : sortByValues(libNormal).entrySet()) { System.out.println(info.getKey() + " = " + info.getValue()); } LinkedHashMap<String, String> libGoogle = new LinkedHashMap<String, String>(); if (cmd.hasOption("google")) { libGoogle = getLibFromPatternInclude(adb, liblist, apkGoogle, Google, "Google", scanlibs); libGoogle = getLibFromPatternGlobalExclude(libGoogle, Google, "Google"); System.out.println(); System.out.println("Final list libraries (Google):"); for (Map.Entry<String, String> info : sortByValues(libGoogle).entrySet()) { System.out.println(info.getKey() + " = " + info.getValue()); } } LinkedHashMap<String, String> apkExclude = new LinkedHashMap<String, String>(apklist); for (String key : apkNormal.keySet()) { apkExclude.remove(key); } for (String key : apkGoogle.keySet()) { apkExclude.remove(key); } System.out.println(); System.out.println("Include libraries from Exclude packages:"); LinkedHashMap<String, String> libExclude = getLibFromPackage(adb, liblist, apkExclude); System.out.println(); System.out.println("Enclude libraries from Exclude packages (Normal):"); for (Map.Entry<String, String> info : sortByValues(libNormal).entrySet()) { if (libExclude.containsKey(info.getKey())) { System.out.println("exclude: " + info.getKey() + " = " + libExclude.get(info.getKey())); libNormal.remove(info.getKey()); } } System.out.println(); System.out.println("Enclude libraries from Exclude packages (Google):"); for (Map.Entry<String, String> info : sortByValues(libGoogle).entrySet()) { if (libExclude.containsKey(info.getKey())) { System.out.println("exclude: " + info.getKey() + " = " + libExclude.get(info.getKey())); libGoogle.remove(info.getKey()); } } System.out.println(); System.out.println("Delete libraries (Normal):"); damage(adb, "rm ", NotTest, libNormal, 1); if (cmd.hasOption("google")) { System.out.println(); System.out.println("Delete libraries (Google):"); damage(adb, "rm ", NotTest, libGoogle, 1); } } if (cmd.hasOption("unapk")) { System.out.println(); System.out.println("Cleaning data packages (Normal):"); damage(adb, "pm clear ", NotTest, apkNormal, 2); if (cmd.hasOption("google")) { System.out.println(); System.out.println("Cleaning data packages (Google):"); damage(adb, "pm clear ", NotTest, apkGoogle, 2); } System.out.println(); System.out.println("Uninstall packages (Normal):"); damage(adb, "pm uninstall ", NotTest, apkNormal, 2); if (cmd.hasOption("google")) { System.out.println(); System.out.println("Uninstall packages (Google):"); damage(adb, "pm uninstall ", NotTest, apkGoogle, 2); } } if (cmd.hasOption("unapk")) { System.out.println(); System.out.println("Delete packages (Normal):"); LinkedHashMap<String, String> dexNormal = new LinkedHashMap<String, String>(); for (Map.Entry<String, String> apk : apkNormal.entrySet()) { dexNormal.put(apk.getKey(), apk.getValue()); dexNormal.put(apk.getKey().replace(".apk", ".dex"), apk.getValue()); dexNormal.put(apk.getKey().replace(".apk", ".odex"), apk.getValue()); } damage(adb, "rm ", NotTest, dexNormal, 1); if (cmd.hasOption("google")) { System.out.println(); System.out.println("Delete packages (Google):"); LinkedHashMap<String, String> dexGoogle = new LinkedHashMap<String, String>(); for (Map.Entry<String, String> apk : apkGoogle.entrySet()) { dexGoogle.put(apk.getKey(), apk.getValue()); dexGoogle.put(apk.getKey().replace(".apk", ".dex"), apk.getValue()); dexGoogle.put(apk.getKey().replace(".apk", ".odex"), apk.getValue()); } damage(adb, "rm ", NotTest, dexGoogle, 1); } } if (NotTest) { run(adb, "-s", lastdevice, "reboot"); } System.out.println(); System.out.println("FINISH :)"); } catch (SAXException e) { System.out.println("Error parsing list: " + e); } catch (Throwable e) { e.printStackTrace(); } }
From source file:cz.muni.fi.mir.mathmlunificator.MathMLUnificatorCommandLineTool.java
/** * Main (starting) method of the command line application. * * @param argv Array of command line arguments that are expected to be * filesystem paths to input XML documents with MathML to be unified. * @throws ParserConfigurationException If a XML DOM builder cannot be * created with the configuration requested. *///from w ww .j a v a2 s .c o m public static void main(String argv[]) throws ParserConfigurationException { final Options options = new Options(); options.addOption("p", "operator-unification", false, "unify operator in addition to other types of nodes"); options.addOption("h", "help", false, "print help"); final CommandLineParser parser = new DefaultParser(); CommandLine line = null; try { line = parser.parse(options, argv); } catch (ParseException ex) { printHelp(options); System.exit(1); } if (line != null) { if (line.hasOption('h')) { printHelp(options); System.exit(0); } operatorUnification = line.hasOption('p'); final List<String> arguments = Arrays.asList(line.getArgs()); if (arguments.size() > 0) { Document outerDocument = DOMBuilder.getDocumentBuilder().newDocument(); Node rootNode = outerDocument.createElementNS(UNIFIED_MATHML_NS, UNIFIED_MATHML_NS_PREFIX + ":" + UNIFIED_MATHML_BATCH_OUTPUT_ROOT_ELEM); outerDocument.appendChild(rootNode); for (String filepath : arguments) { try { Document doc = DOMBuilder.buildDocFromFilepath(filepath); MathMLUnificator.unifyMathML(doc, operatorUnification); if (arguments.size() == 1) { xmlStdoutSerializer(doc); } else { Node itemNode = rootNode.getOwnerDocument().createElementNS(UNIFIED_MATHML_NS, UNIFIED_MATHML_NS_PREFIX + ":" + UNIFIED_MATHML_BATCH_OUTPUT_ITEM_ELEM); Attr filenameAttr = itemNode.getOwnerDocument().createAttributeNS(UNIFIED_MATHML_NS, UNIFIED_MATHML_NS_PREFIX + ":" + UNIFIED_MATHML_BATCH_OUTPUT_ITEM_FILEPATH_ATTR); filenameAttr.setTextContent(String.valueOf(filepath)); ((Element) itemNode).setAttributeNodeNS(filenameAttr); itemNode.appendChild( rootNode.getOwnerDocument().importNode(doc.getDocumentElement(), true)); rootNode.appendChild(itemNode); } } catch (SAXException | IOException ex) { Logger.getLogger(MathMLUnificatorCommandLineTool.class.getName()).log(Level.SEVERE, "Failed processing of file: " + filepath, ex); } } if (rootNode.getChildNodes().getLength() > 0) { xmlStdoutSerializer(rootNode.getOwnerDocument()); } } else { printHelp(options); System.exit(0); } } }
From source file:Main.java
public static void visit(Node node, int level) { NodeList list = node.getChildNodes(); for (int i = 0; i < list.getLength(); i++) { Node childNode = list.item(i); visit(childNode, level + 1);/*from w w w . jav a 2 s .c o m*/ } }
From source file:Main.java
public static void visit(Node node, int level) { NodeList list = node.getChildNodes(); for (int i = 0; i < list.getLength(); i++) { Node childNode = list.item(i); System.out.println(childNode); visit(childNode, level + 1);//from w w w . ja v a2 s.com } }
From source file:Main.java
private static boolean hasOnlyOneTextNode(Node node) { return node.getChildNodes().getLength() == 1 && node.getChildNodes().item(0).getNodeType() == Node.TEXT_NODE; }
From source file:Main.java
public static void removeAll(Node node) { while (node.getChildNodes().getLength() > 0) { node.removeChild(node.getFirstChild()); }// w w w. j a v a 2s . c o m }
From source file:Main.java
public static String getContents(Node node) { String s = node.getChildNodes().item(0).getTextContent(); if (s != null) { return s.trim(); }//ww w . jav a2s .c om return null; }