List of usage examples for org.w3c.dom Node getFirstChild
public Node getFirstChild();
From source file:Main.java
public static void main(String args[]) throws IOException, SAXException { DOMParser parser = new DOMParser(); parser.parse("games.xml"); Document dom = parser.getDocument(); NodeList games = dom.getElementsByTagName("game"); for (int i = 0; i < games.getLength(); i++) { Node aNode = games.item(i); System.out.println(aNode.getFirstChild().getNodeValue()); NamedNodeMap attributes = aNode.getAttributes(); for (int a = 0; a < attributes.getLength(); a++) { Node theAttribute = attributes.item(a); System.out.println(theAttribute.getNodeName() + "=" + theAttribute.getNodeValue()); }// w w w . j a va2 s . c o m } }
From source file:Main.java
public static void main(String[] args) throws Exception { DocumentBuilderFactory Factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = Factory.newDocumentBuilder(); Document doc = builder.parse("myxml.xml"); XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); XPathExpression expr = xpath.compile("//" + "item1" + "/*"); Object result = expr.evaluate(doc, XPathConstants.NODESET); NodeList nodes = (NodeList) result; System.out.println(nodes.getLength()); for (int i = 0; i < nodes.getLength(); i++) { Element el = (Element) nodes.item(i); System.out.println("tag: " + el.getNodeName()); if (el.getFirstChild().getNodeType() == Node.TEXT_NODE) System.out.println("inner value:" + el.getFirstChild().getNodeValue()); NodeList children = el.getChildNodes(); for (int k = 0; k < children.getLength(); k++) { Node child = children.item(k); if (child.getNodeType() != Node.TEXT_NODE) { System.out.println("child tag: " + child.getNodeName()); if (child.getFirstChild().getNodeType() == Node.TEXT_NODE) System.out.println("inner child value:" + child.getFirstChild().getNodeValue()); }//from www. j a v a 2s . c om } } }
From source file:Main.java
public static void main(String[] argv) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(true);/* w w w . j a v a 2 s . co m*/ Document doc = factory.newDocumentBuilder().parse(new File("infilename.xml")); String fragment = "<fragment>aaa</fragment>"; factory = DocumentBuilderFactory.newInstance(); Document d = factory.newDocumentBuilder().parse(new InputSource(new StringReader(fragment))); Node node = doc.importNode(d.getDocumentElement(), true); DocumentFragment docfrag = doc.createDocumentFragment(); while (node.hasChildNodes()) { docfrag.appendChild(node.removeChild(node.getFirstChild())); } Element element = doc.getDocumentElement(); element.appendChild(docfrag); }
From source file:MainClass.java
public static void main(String[] args) throws IOException, ParserConfigurationException, org.xml.sax.SAXException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setIgnoringComments(true);/* w w w .jav a 2s . com*/ factory.setCoalescing(true); // Convert CDATA to Text nodes factory.setNamespaceAware(false); // No namespaces: this is default factory.setValidating(false); // Don't validate DTD: also default DocumentBuilder parser = factory.newDocumentBuilder(); Document document = parser.parse(new File(args[0])); NodeList sections = document.getElementsByTagName("sect1"); int numSections = sections.getLength(); for (int i = 0; i < numSections; i++) { Element section = (Element) sections.item(i); // A <sect1> Node title = section.getFirstChild(); while (title != null && title.getNodeType() != Node.ELEMENT_NODE) title = title.getNextSibling(); if (title != null) System.out.println(title.getFirstChild().getNodeValue()); } }
From source file:Main.java
public static void main(String[] argv) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(true);/* w w w .ja v a 2 s. c o 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 . j a v a2s. 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 w ww. j a va 2 s .c om*/ 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:ListMoviesXML.java
private static String getTextValue(Node n) { return n.getFirstChild().getNodeValue(); }
From source file:Main.java
public static Element getNextChildElement(Node node) { Node n = node.getFirstChild(); while (n != null && n.getNodeType() != Node.ELEMENT_NODE) { n = n.getNextSibling();// w ww . j ava 2 s.c o m } return (Element) n; }
From source file:Main.java
public static String getTextContent(Node node) { Node n = node.getFirstChild(); if (n == null) return ""; String s = n.getNodeValue();/*w w w . ja va2s. c om*/ if (s == null) s = ""; return s; }