List of usage examples for org.w3c.dom NodeList getLength
public int getLength();
From source file:Main.java
public static void main(String argv[]) throws Exception { String next = "keyword,123"; String[] input = next.split(","); String textToFind = input[0].replace("'", "\\'"); // "CEO"; String textToReplace = input[1].replace("'", "\\'"); // "Chief Executive Officer"; String filepath = "root.xml"; String fileToBeSaved = "root2.xml"; DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.parse(filepath); XPath xpath = XPathFactory.newInstance().newXPath(); // change ELEMENTS String xPathExpression = "//*[text()='" + textToFind + "']"; NodeList nodes = (NodeList) xpath.evaluate(xPathExpression, doc, XPathConstants.NODESET); for (int idx = 0; idx < nodes.getLength(); idx++) { nodes.item(idx).setTextContent(textToReplace); }/* ww w . j a v a 2s .c om*/ // change ATTRIBUTES String xPathExpressionAttr = "//*/@*[.='" + textToFind + "']"; NodeList nodesAttr = (NodeList) xpath.evaluate(xPathExpressionAttr, doc, XPathConstants.NODESET); for (int i = 0; i < nodesAttr.getLength(); i++) { nodesAttr.item(i).setTextContent(textToReplace); } System.out.println("Everything replaced."); // save xml file back TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(new File(fileToBeSaved)); transformer.transform(source, result); }
From source file:Main.java
public static void main(String[] args) throws Exception { InputSource source = new InputSource(new StringReader("<root>\n" + "<field name='firstname'>\n" + " <value>John</value>\n" + "</field>\n" + "<field name='lastname'>\n" + " <value>Citizen</value>\n" + "</field>\n" + "<field name='DoB'>\n" + " <value>01/01/1980</value>\n" + "</field>\n" + "<field name='Profession'>\n" + " <value>Manager</value>\n" + "</field>\n" + "</root>")); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = factory.newDocumentBuilder(); Document document = documentBuilder.parse(source); NodeList allFields = (NodeList) document.getElementsByTagName("field"); Map<String, String> data = new HashMap<>(); for (int i = 0; i < allFields.getLength(); i++) { Element field = (Element) allFields.item(i); String nameAttribute = field.getAttribute("name"); Element child = (Element) field.getElementsByTagName("value").item(0); String value = child.getTextContent(); data.put(nameAttribute, value);/* w w w .j a v a 2s.co m*/ } for (Map.Entry field : data.entrySet()) { System.out.println(field.getKey() + ": " + field.getValue()); } }
From source file:GuestList.java
public static void main(String[] args) throws Exception { XPathFactory factory = XPathFactory.newInstance(); XPath xPath = factory.newXPath(); NodeList shows = (NodeList) xPath.evaluate("/schedule/show", new InputSource(new FileReader("tds.xml")), XPathConstants.NODESET); for (int i = 0; i < shows.getLength(); i++) { Element show = (Element) shows.item(i); String guestName = xPath.evaluate("guest/name", show); String guestCredit = xPath.evaluate("guest/credit", show); System.out.println(show.getAttribute("weekday") + ", " + show.getAttribute("date") + " - " + guestName + " (" + guestCredit + ")"); }//from ww w . j a v a 2 s . c o m }
From source file:XMLInfo.java
public static void main(String args[]) { try {/* w ww. ja v a2 s. c o 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:com.twitter.hraven.hadoopJobMonitor.rpc.RestClient.java
/** * Used for testing the RestClient/*w w w . j a v a2s.co m*/ * * @param args * @throws Exception */ public static void main(String[] args) throws Exception { Document xmlDoc = RestClient.getInstance() .getXml("http://localhost:8080/" + "ws/v1/history/mapreduce/jobs/job_1389724922546_0058/"); // Iterating through the nodes and extracting the data. NodeList nodeList = xmlDoc.getDocumentElement().getChildNodes(); for (int i = 0; i < nodeList.getLength(); i++) { // We have encountered an <employee> tag. Node node = nodeList.item(i); if (node instanceof Element) { System.out.println(node.getNodeName() + " = " + node.getTextContent()); } } }
From source file:Main.java
public static void main(String[] args) throws Exception { List<Car> carsList = new ArrayList<Car>(); Set<Car> carsset = new HashSet<Car>(); File fXmlFile = new File("cars.xml"); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(fXmlFile); doc.getDocumentElement().normalize(); NodeList nList = doc.getElementsByTagName("cars"); Car tempCar = null;/*from w w w. j a va2s.c o m*/ for (int temp = 0; temp < nList.getLength(); temp++) { Node nNode = nList.item(temp); if (nNode.getNodeType() == Node.ELEMENT_NODE) { tempCar = new Car(); Element eElement = (Element) nNode; tempCar.setModel(eElement.getElementsByTagName("model").item(0).getTextContent()); tempCar.setVersion(eElement.getElementsByTagName("version").item(0).getTextContent()); carsList.add(tempCar); carsset.add(tempCar); } } for (Car cs : carsset) { int count = 0; for (Car cl : carsList) { if (cs.equals(cl)) { count = count + 1; } } System.out.println(cs + "\t" + count); } }
From source file:TestDOM.java
public static void main(String[] args) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder parser = factory.newDocumentBuilder(); Document document = parser.parse("zooinventory.xml"); Element inventory = document.getDocumentElement(); NodeList animals = inventory.getElementsByTagName("Animal"); System.out.println("Animals = "); for (int i = 0; i < animals.getLength(); i++) { String name = DOMUtil.getSimpleElementText((Element) animals.item(i), "Name"); String species = DOMUtil.getSimpleElementText((Element) animals.item(i), "Species"); System.out.println(" " + name + " (" + species + ")"); }/*from w w w. j a v a 2 s. c o m*/ Element foodRecipe = DOMUtil.getFirstElement((Element) animals.item(1), "FoodRecipe"); String name = DOMUtil.getSimpleElementText(foodRecipe, "Name"); System.out.println("Recipe = " + name); NodeList ingredients = foodRecipe.getElementsByTagName("Ingredient"); for (int i = 0; i < ingredients.getLength(); i++) System.out.println(" " + DOMUtil.getSimpleElementText((Element) ingredients.item(i))); }
From source file:edu.ucsb.cs.eager.sa.cerebro.ProfessorX.java
public static void main(String[] args) { Options options = new Options(); options.addOption("i", "input-file", true, "Path to input xml file"); options.addOption("r", "root-path", true, "Root path of all Git repositories"); CommandLine cmd;//from ww w . j ava 2 s . c o m try { CommandLineParser parser = new BasicParser(); cmd = parser.parse(options, args); } catch (ParseException e) { System.err.println("Error: " + e.getMessage() + "\n"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("Cerebro", options); return; } String inputFileName = cmd.getOptionValue("i"); if (inputFileName == null) { System.err.println("input file path is required"); return; } String rootPath = cmd.getOptionValue("r"); if (rootPath == null) { System.err.println("root path is required"); return; } File inputFile = new File(inputFileName); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); Document doc; try { DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); doc = dBuilder.parse(inputFile); } catch (Exception e) { System.err.println(e.getMessage()); e.printStackTrace(); return; } NodeList repoList = doc.getElementsByTagName("repo"); for (int i = 0; i < repoList.getLength(); i++) { Element repo = (Element) repoList.item(i); String name = repo.getElementsByTagName("name").item(0).getTextContent(); String classPath = repo.getElementsByTagName("classpath").item(0).getTextContent(); Set<String> classes = new LinkedHashSet<String>(); NodeList classesList = repo.getElementsByTagName("classes").item(0).getChildNodes(); for (int j = 0; j < classesList.getLength(); j++) { if (!(classesList.item(j) instanceof Element)) { continue; } classes.add(classesList.item(j).getTextContent()); } analyzeRepo(rootPath, name, classPath, classes); } }
From source file:com.amazon.advertising.api.sample.ItemLookupSample.java
public static void main(String[] args) { /*/*from w w w . jav a 2s .c o m*/ * Set up the signed requests helper */ SignedRequestsHelper helper; try { helper = SignedRequestsHelper.getInstance(ENDPOINT, AWS_ACCESS_KEY_ID, AWS_SECRET_KEY); } catch (Exception e) { e.printStackTrace(); return; } String requestUrl = null; String title = null; /* The helper can sign requests in two forms - map form and string form */ /* * Here is an example in map form, where the request parameters are stored in a map. */ System.out.println("Map form example:"); Map<String, String> params = new HashMap<String, String>(); params.put("Service", "AWSECommerceService"); params.put("Version", "2011-08-01"); params.put("Operation", "ItemSearch"); params.put("SearchIndex", "Books"); params.put("Keywords", "Harry"); // params.put("ResponseGroup", "Small"); requestUrl = helper.sign(params); // System.out.println("Signed Request is \"" + requestUrl + "\""); // title = fetchTitle(requestUrl); // System.out.println("Signed Title is \"" + title + "\""); // System.out.println(); /* Here is an example with string form, where the requests parameters have already been concatenated * into a query string. */ // System.out.println("String form example:"); // String queryString = "Service=AWSECommerceService&Version=2009-03-31&Operation=ItemSearch&ResponseGroup=Small&SearchIndex=Books&keywords=harry" // + ITEM_ID; // requestUrl = helper.sign(queryString); NodeList nodelist = fetchASIN(requestUrl); System.out.println(nodelist.getLength()); for (int i = 0; i < nodelist.getLength(); i++) { String asin = nodelist.item(i).getTextContent(); println(asin); getItemInfo(asin, helper); break; } }
From source file:OldExtractor.java
/** * @param args the command line arguments *///from w ww .j a v a 2s.co m public static void main(String[] args) { // TODO code application logic here String bingUrl = "https://api.datamarket.azure.com/Bing/Search/Web?$top=10&$format=Atom&Query=%27gates%27"; //Provide your account key here. String accountKey = "ghTYY7wD6LpyxUO9VRR7e1f98WFhHWYERMcw87aQTqQ"; // String accountKey = "xqbCjT87/MQz25JWdRzgMHdPkGYnOz77IYmP5FUIgC8"; byte[] accountKeyBytes = Base64.encodeBase64((accountKey + ":" + accountKey).getBytes()); String accountKeyEnc = new String(accountKeyBytes); try { URL url = new URL(bingUrl); URLConnection urlConnection = url.openConnection(); urlConnection.setRequestProperty("Authorization", "Basic " + accountKeyEnc); InputStream inputStream = (InputStream) urlConnection.getContent(); byte[] contentRaw = new byte[urlConnection.getContentLength()]; inputStream.read(contentRaw); String content = new String(contentRaw); //System.out.println(content); try { File file = new File("Results.xml"); FileWriter fileWriter = new FileWriter(file); fileWriter.write(content); //fileWriter.write("a test"); fileWriter.flush(); fileWriter.close(); } catch (IOException e) { System.out.println(e); } DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); try { //System.out.println("here"); //Using factory get an instance of document builder DocumentBuilder db = dbf.newDocumentBuilder(); //parse using builder to get DOM representation of the XML file Document dom = db.parse("Results.xml"); Element docEle = (Element) dom.getDocumentElement(); //get a nodelist of elements NodeList nl = docEle.getElementsByTagName("d:Url"); if (nl != null && nl.getLength() > 0) { for (int i = 0; i < nl.getLength(); i++) { //get the employee element Element el = (Element) nl.item(i); // System.out.println("here"); System.out.println(el.getTextContent()); //get the Employee object //Employee e = getEmployee(el); //add it to list //myEmpls.add(e); } } NodeList n2 = docEle.getElementsByTagName("d:Title"); if (n2 != null && n2.getLength() > 0) { for (int i = 0; i < n2.getLength(); i++) { //get the employee element Element e2 = (Element) n2.item(i); // System.out.println("here"); System.out.println(e2.getTextContent()); //get the Employee object //Employee e = getEmployee(el); //add it to list //myEmpls.add(e); } } NodeList n3 = docEle.getElementsByTagName("d:Description"); if (n3 != null && n3.getLength() > 0) { for (int i = 0; i < n3.getLength(); i++) { //get the employee element Element e3 = (Element) n3.item(i); // System.out.println("here"); System.out.println(e3.getTextContent()); //get the Employee object //Employee e = getEmployee(el); //add it to list //myEmpls.add(e); } } } catch (SAXException se) { se.printStackTrace(); } catch (ParserConfigurationException pe) { pe.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } } catch (IOException e) { System.out.println(e); } //The content string is the xml/json output from Bing. }