List of usage examples for org.w3c.dom Document getDocumentElement
public Element getDocumentElement();
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(new File("testrss.xml")); Element root = doc.getDocumentElement(); if (!root.getTagName().equalsIgnoreCase("rss")) { throw new IOException("Invalid RSS document"); }/* ww w . ja va 2 s . co m*/ List<RSSChannel> channels = readChannels(root.getChildNodes()); for (RSSChannel channel : channels) { System.out.println("Channel: "); System.out.println(" title: " + channel.getTitle()); System.out.println(" link: " + channel.getLink()); System.out.println(" description: " + channel.getDescription()); for (RSSItem item : channel.getItems()) { System.out.println(" Item: "); System.out.println(" title: " + item.getTitle()); System.out.println(" link: " + item.getLink()); System.out.println(" description: " + item.getDescription()); System.out.println(" pubDate: " + item.getPubDate()); System.out.println(" guid: " + item.getGuid()); } } }
From source file:Main.java
public static void main(String[] args) throws Exception { DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance(); dFactory.setValidating(false);/*ww w .j a va 2 s . c o m*/ DocumentBuilder dBuilder = dFactory.newDocumentBuilder(); Document dDoc = dBuilder.newDocument(); // The root document element. Element pageDataElement = dDoc.createElement("page-data"); pageDataElement.appendChild(dDoc.createTextNode("Example Text.")); dDoc.appendChild(pageDataElement); System.out.println(dDoc.getDocumentElement().getTextContent()); }
From source file:Signing.java
public static void main(String[] args) throws Exception { SOAPMessage soapMessage = MessageFactory.newInstance().createMessage(); SOAPPart soapPart = soapMessage.getSOAPPart(); SOAPEnvelope soapEnvelope = soapPart.getEnvelope(); SOAPHeader soapHeader = soapEnvelope.getHeader(); SOAPHeaderElement headerElement = soapHeader.addHeaderElement(soapEnvelope.createName("Signature", "SOAP-SEC", "http://schemas.xmlsoap.org/soap/security/2000-12")); SOAPBody soapBody = soapEnvelope.getBody(); soapBody.addAttribute(//from www . j a v a 2s . co m soapEnvelope.createName("id", "SOAP-SEC", "http://schemas.xmlsoap.org/soap/security/2000-12"), "Body"); Name bodyName = soapEnvelope.createName("FooBar", "z", "http://example.com"); SOAPBodyElement gltp = soapBody.addBodyElement(bodyName); Source source = soapPart.getContent(); Node root = null; if (source instanceof DOMSource) { root = ((DOMSource) source).getNode(); } else if (source instanceof SAXSource) { InputSource inSource = ((SAXSource) source).getInputSource(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder db = null; db = dbf.newDocumentBuilder(); Document doc = db.parse(inSource); root = (Node) doc.getDocumentElement(); } dumpDocument(root); KeyPairGenerator kpg = KeyPairGenerator.getInstance("DSA"); kpg.initialize(1024, new SecureRandom()); KeyPair keypair = kpg.generateKeyPair(); XMLSignatureFactory sigFactory = XMLSignatureFactory.getInstance(); Reference ref = sigFactory.newReference("#Body", sigFactory.newDigestMethod(DigestMethod.SHA1, null)); SignedInfo signedInfo = sigFactory.newSignedInfo( sigFactory.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS, (C14NMethodParameterSpec) null), sigFactory.newSignatureMethod(SignatureMethod.DSA_SHA1, null), Collections.singletonList(ref)); KeyInfoFactory kif = sigFactory.getKeyInfoFactory(); KeyValue kv = kif.newKeyValue(keypair.getPublic()); KeyInfo keyInfo = kif.newKeyInfo(Collections.singletonList(kv)); XMLSignature sig = sigFactory.newXMLSignature(signedInfo, keyInfo); System.out.println("Signing the message..."); PrivateKey privateKey = keypair.getPrivate(); Element envelope = getFirstChildElement(root); Element header = getFirstChildElement(envelope); DOMSignContext sigContext = new DOMSignContext(privateKey, header); sigContext.putNamespacePrefix(XMLSignature.XMLNS, "ds"); sigContext.setIdAttributeNS(getNextSiblingElement(header), "http://schemas.xmlsoap.org/soap/security/2000-12", "id"); sig.sign(sigContext); dumpDocument(root); System.out.println("Validate the signature..."); Element sigElement = getFirstChildElement(header); DOMValidateContext valContext = new DOMValidateContext(keypair.getPublic(), sigElement); valContext.setIdAttributeNS(getNextSiblingElement(header), "http://schemas.xmlsoap.org/soap/security/2000-12", "id"); boolean valid = sig.validate(valContext); System.out.println("Signature valid? " + valid); }
From source file:Main.java
License:asdf
public static void main(String[] args) throws Exception { String initial = "<root><param value=\"abc\"/><param value=\"bc\"/></root>"; ByteArrayInputStream is = new ByteArrayInputStream(initial.getBytes()); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(is); // Create the new xml fragment Text a = doc.createTextNode("asdf"); Node p = doc.createElement("parameterDesc"); p.appendChild(a);//from ww w .ja va 2 s . c o m Node i = doc.createElement("insert"); i.appendChild(p); Element r = doc.getDocumentElement(); r.insertBefore(i, r.getFirstChild()); r.normalize(); // Format the xml for output Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); // initialize StreamResult with File object to save to file StreamResult result = new StreamResult(new StringWriter()); DOMSource source = new DOMSource(doc); transformer.transform(source, result); System.out.println(result.getWriter().toString()); }
From source file:OldExtractor.java
/** * @param args the command line arguments *//*w ww .j av a 2 s. c o 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. }
From source file:com.twitter.hraven.hadoopJobMonitor.rpc.RestClient.java
/** * Used for testing the RestClient/*from ww w. ja v a2s .com*/ * * @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[] argv) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(true);//from w w w . jav a 2 s .co m factory.setExpandEntityReferences(false); Document doc = factory.newDocumentBuilder().parse(new File("filename")); Element root = null; NodeList list = doc.getChildNodes(); for (int i = 0; i < list.getLength(); i++) { if (list.item(i) instanceof Element) { root = (Element) list.item(i); break; } } root = doc.getDocumentElement(); }
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(new File("in.xml")); TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(); transformer.setOutputProperty("indent", "yes"); StringWriter sw = new StringWriter(); StreamResult result = new StreamResult(sw); NodeList nl = doc.getDocumentElement().getChildNodes(); DOMSource source = null;/* w w w. j a v a2 s . c o m*/ for (int x = 0; x < nl.getLength(); x++) { Node e = nl.item(x); if (e instanceof Element) { source = new DOMSource(e); break; } } transformer.transform(source, result); System.out.println(sw.toString()); }
From source file:MainClass.java
public static void main(String args[]) throws IOException { Document dom = DOMImplementation.createDocument(null, null, null); Element root = dom.createElement("A"); Element child1 = dom.createElement("B"); child1.appendChild(dom.createTextNode("C")); child1.setAttribute("A", "a"); root.appendChild(child1);//from ww w .j av a 2 s.c o m dom.appendChild(root); XMLSerializer serial = new XMLSerializer(System.out, null); serial.serialize(dom.getDocumentElement()); }
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 .ja v a2 s .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(); } }