List of usage examples for org.w3c.dom Document getElementsByTagName
public NodeList getElementsByTagName(String tagname);
NodeList
of all the Elements
in document order with a given tag name and are contained in the document. From source file:Main.java
public static void main(String args[]) throws Exception { File stocks = new File("Stocks.xml"); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(stocks); doc.getDocumentElement().normalize(); System.out.println(doc.getDocumentElement().getNodeName()); NodeList nodes = doc.getElementsByTagName("stock"); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { Element element = (Element) node; System.out.println("Stock Symbol: " + getValue("symbol", element)); System.out.println("Stock Price: " + getValue("price", element)); System.out.println("Stock Quantity: " + getValue("quantity", element)); }//from ww w . j a va 2s . co m } }
From source file:Main.java
public static void main(String[] args) throws Exception { File fXmlFile = new File("data.xml"); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(fXmlFile); doc.getDocumentElement().normalize(); System.out.println("Root element :" + doc.getDocumentElement().getNodeName()); NodeList nList = doc.getElementsByTagName("Employee"); for (int temp = 0; temp < nList.getLength(); temp++) { System.out.println(nodeToString(nList.item(temp))); }//from ww w .java 2 s.co m }
From source file:Main.java
public static void main(String[] args) throws Exception { DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = db.parse(new InputSource( new StringReader("<emp><empname><firstName></firstName><lastName></lastName></empname></emp>"))); NodeList customerNodes = doc.getElementsByTagName("empname"); for (int i = 0; i < customerNodes.getLength(); i++) { NodeList children = customerNodes.item(i).getChildNodes(); for (int j = 0; j < children.getLength(); j++) { String childNode = children.item(j).getNodeName(); if (childNode.equalsIgnoreCase("firstName")) { children.item(j).setTextContent(String.valueOf("John")); } else if (childNode.equalsIgnoreCase("lastName")) { children.item(j).setTextContent(String.valueOf("Doe")); }/*from w w w.j a va 2s . co m*/ } } TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); StringWriter writer = new StringWriter(); transformer.transform(new DOMSource(doc), new StreamResult(writer)); System.out.println(writer.getBuffer().toString()); }
From source file:Main.java
public static void main(String argv[]) throws Exception { File myfile = new File("data.xml"); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(myfile); doc.getDocumentElement().normalize(); System.out.println("Root element :" + doc.getDocumentElement().getNodeName()); NodeList nList = doc.getElementsByTagName("test"); for (int temp = 0; temp < nList.getLength(); temp++) { Node nNode = nList.item(temp); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; System.out.println("First Name : " + getTagValue("id", eElement)); System.out.println("Last Name : " + getTagValue("result", eElement)); }/*from ww w. ja va 2 s . c o m*/ } }
From source file:Main.java
public static void main(String argv[]) throws Exception { File fXmlFile = new File("data.xml"); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(fXmlFile); doc.getDocumentElement().normalize(); System.out.println("Root element :" + doc.getDocumentElement().getNodeName()); NodeList nList = doc.getElementsByTagName("staff"); for (int temp = 0; temp < nList.getLength(); temp++) { Node nNode = nList.item(temp); System.out.println("\nCurrent Element :" + nNode.getNodeName()); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; System.out.println("Staff id : " + eElement.getAttribute("id")); System.out.println(/*from w w w . j a va2 s. c om*/ "First Name : " + eElement.getElementsByTagName("firstname").item(0).getTextContent()); System.out.println( "Last Name : " + eElement.getElementsByTagName("lastname").item(0).getTextContent()); System.out.println( "Nick Name : " + eElement.getElementsByTagName("nickname").item(0).getTextContent()); System.out.println("Salary : " + eElement.getElementsByTagName("salary").item(0).getTextContent()); } } }
From source file:Main.java
public static void main(String[] argv) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(true);/* w ww . j a v a 2 s .c o m*/ factory.setExpandEntityReferences(false); Document doc = factory.newDocumentBuilder().parse(new File("filename")); Element element = doc.getDocumentElement(); ProcessingInstruction pi = doc.createProcessingInstruction("target", "instruction"); NodeList list = doc.getElementsByTagName("entry"); for (int i = 0; i < list.getLength(); i++) { element = (Element) list.item(i); pi = doc.createProcessingInstruction("target", "instruction=" + i); element.appendChild(pi); } }
From source file:Main.java
public static void main(String[] args) throws Exception { String xml = "<Services><service name='qwerty' id=''><File rootProfile='abcd' extension='acd'><Columns>" + "<name id='0' profileName='DATE' type='java'></name><name id='1' profileName='DATE' type='java'></name>" + "</Columns></File><File rootProfile='efg' extension='ghi'><Columns><name id='a' profileName='DATE' type='java'></name>" + "<name id='b' profileName='DATE' type='java'></name></Columns></File></service></Services>"; DocumentBuilderFactory documentFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = null; documentBuilder = documentFactory.newDocumentBuilder(); org.w3c.dom.Document doc = documentBuilder.parse(new InputSource(new ByteArrayInputStream(xml.getBytes()))); doc.getDocumentElement().normalize(); NodeList nodeList0 = doc.getElementsByTagName("service"); NodeList nodeList1 = null;//w w w. j ava 2 s.c o m NodeList nodeList2 = null; System.out.println("Root element :" + doc.getDocumentElement().getNodeName()); for (int temp0 = 0; temp0 < nodeList0.getLength(); temp0++) { Node node0 = nodeList0.item(temp0); System.out.println("\nElement type :" + node0.getNodeName()); Element Service = (Element) node0; if (node0.getNodeType() != Node.ELEMENT_NODE) { continue; } System.out.println("name : " + Service.getAttribute("name")); System.out.println("id : " + Service.getAttribute("id")); nodeList1 = Service.getChildNodes(); for (int temp = 0; temp < nodeList1.getLength(); temp++) { Node node1 = nodeList1.item(temp); System.out.println("\nElement type :" + node1.getNodeName()); Element File = (Element) node1; if (node1.getNodeType() != Node.ELEMENT_NODE) { continue; } System.out.println("rootProfile:" + File.getAttribute("rootProfile")); System.out.println("extension : " + File.getAttribute("extension")); nodeList2 = File.getChildNodes();// colums for (int temp1 = 0; temp1 < nodeList2.getLength(); temp1++) { Element column = (Element) nodeList2.item(temp1); NodeList nodeList4 = column.getChildNodes(); for (int temp3 = 0; temp3 < nodeList4.getLength(); temp3++) { Element name = (Element) nodeList4.item(temp3); if (name.getNodeType() != Node.ELEMENT_NODE) { continue; } System.out.println("id:" + name.getAttribute("id")); System.out.println("profileName : " + name.getAttribute("profileName")); System.out.println("type : " + name.getAttribute("type")); } } } } }
From source file:Main.java
public static void main(String[] args) throws Exception { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(new InputSource(new StringReader(cfgXml))); doc.getDocumentElement().normalize(); System.out.println("Root element :" + doc.getDocumentElement().getNodeName()); NodeList nList = doc.getElementsByTagName("config"); for (int temp = 0; temp < nList.getLength(); temp++) { Node nNode = nList.item(temp); System.out.println("\nCurrent Element :" + nNode.getNodeName()); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; Config c = new Config(); c.name = eElement.getAttribute("name"); c.type = eElement.getAttribute("type"); c.format = eElement.getAttribute("format"); c.size = Integer.valueOf(eElement.getAttribute("size")); c.scale = Integer.valueOf(eElement.getAttribute("scale")); String attribute = eElement.getAttribute("required"); c.required = Boolean.valueOf("Yes".equalsIgnoreCase(attribute) ? true : false); System.out.println("Imported config : " + c); }//from w w w . j a va 2 s. c o m } }
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.ja va2 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:ValidateLicenseHeaders.java
/** * ValidateLicenseHeaders jboss-src-root * //from w ww. ja v a2 s . c o m * @param args */ public static void main(String[] args) throws Exception { if (args.length == 0 || args[0].startsWith("-h")) { log.info("Usage: ValidateLicenseHeaders [-addheader] jboss-src-root"); System.exit(1); } int rootArg = 0; if (args.length == 2) { if (args[0].startsWith("-add")) addDefaultHeader = true; else { log.severe("Uknown argument: " + args[0]); log.info("Usage: ValidateLicenseHeaders [-addheader] jboss-src-root"); System.exit(1); } rootArg = 1; } File jbossSrcRoot = new File(args[rootArg]); if (jbossSrcRoot.exists() == false) { log.info("Src root does not exist, check " + jbossSrcRoot.getAbsolutePath()); System.exit(1); } URL u = Thread.currentThread().getContextClassLoader() .getResource("META-INF/services/javax.xml.parsers.DocumentBuilderFactory"); System.err.println(u); // Load the valid copyright statements for the licenses File licenseInfo = new File(jbossSrcRoot, "varia/src/etc/license-info.xml"); if (licenseInfo.exists() == false) { log.severe("Failed to find the varia/src/etc/license-info.xml under the src root"); System.exit(1); } DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder db = factory.newDocumentBuilder(); Document doc = db.parse(licenseInfo); NodeList licenses = doc.getElementsByTagName("license"); for (int i = 0; i < licenses.getLength(); i++) { Element license = (Element) licenses.item(i); String key = license.getAttribute("id"); ArrayList headers = new ArrayList(); licenseHeaders.put(key, headers); NodeList copyrights = license.getElementsByTagName("terms-header"); for (int j = 0; j < copyrights.getLength(); j++) { Element copyright = (Element) copyrights.item(j); copyright.normalize(); String id = copyright.getAttribute("id"); // The id will be blank if there is no id attribute if (id.length() == 0) continue; String text = getElementContent(copyright); if (text == null) continue; // Replace all duplicate whitespace and '*' with a single space text = text.replaceAll("[\\s*]+", " "); if (text.length() == 1) continue; text = text.toLowerCase().trim(); // Replace any copyright date0-date1,date2 with copyright ... text = text.replaceAll(COPYRIGHT_REGEX, "..."); LicenseHeader lh = new LicenseHeader(id, text); headers.add(lh); } } log.fine(licenseHeaders.toString()); File[] files = jbossSrcRoot.listFiles(dotJavaFilter); log.info("Root files count: " + files.length); processSourceFiles(files, 0); log.info("Processed " + totalCount); log.info("Updated jboss headers: " + jbossCount); // Files with no headers details log.info("Files with no headers: " + noheaders.size()); FileWriter fw = new FileWriter("NoHeaders.txt"); for (Iterator iter = noheaders.iterator(); iter.hasNext();) { File f = (File) iter.next(); fw.write(f.getAbsolutePath()); fw.write('\n'); } fw.close(); // Files with unknown headers details log.info("Files with invalid headers: " + invalidheaders.size()); fw = new FileWriter("InvalidHeaders.txt"); for (Iterator iter = invalidheaders.iterator(); iter.hasNext();) { File f = (File) iter.next(); fw.write(f.getAbsolutePath()); fw.write('\n'); } fw.close(); // License usage summary log.info("Creating HeadersSummary.txt"); fw = new FileWriter("HeadersSummary.txt"); for (Iterator iter = licenseHeaders.entrySet().iterator(); iter.hasNext();) { Map.Entry entry = (Map.Entry) iter.next(); String key = (String) entry.getKey(); fw.write("+++ License type=" + key); fw.write('\n'); List list = (List) entry.getValue(); Iterator jiter = list.iterator(); while (jiter.hasNext()) { LicenseHeader lh = (LicenseHeader) jiter.next(); fw.write('\t'); fw.write(lh.id); fw.write(", count="); fw.write("" + lh.count); fw.write('\n'); } } fw.close(); }