List of usage examples for org.w3c.dom Document getChildNodes
public NodeList getChildNodes();
NodeList
that contains all children of this node. From source file:org.zaizi.oauth2utils.OAuthUtils.java
public static void parseXMLDoc(Element element, Document doc, Map<String, String> oauthResponse) { NodeList child = null;//from www .j av a 2 s . co m if (element == null) { child = doc.getChildNodes(); } else { child = element.getChildNodes(); } for (int j = 0; j < child.getLength(); j++) { if (child.item(j).getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) { org.w3c.dom.Element childElement = (org.w3c.dom.Element) child.item(j); if (childElement.hasChildNodes()) { System.out.println(childElement.getTagName() + " : " + childElement.getTextContent()); oauthResponse.put(childElement.getTagName(), childElement.getTextContent()); parseXMLDoc(childElement, null, oauthResponse); } } } }
From source file:Main.java
/** * Try to normalize a document by removing nonsignificant whitespace. * * @see "#62006"// w w w . j ava 2 s . c o m */ private static Document normalize(Document orig) throws IOException { DocumentBuilder builder = null; DocumentBuilderFactory factory = getFactory(false, false); try { builder = factory.newDocumentBuilder(); } catch (ParserConfigurationException e) { throw new IOException("Cannot create parser satisfying configuration parameters: " + e, e); //NOI18N } DocumentType doctype = null; NodeList nl = orig.getChildNodes(); for (int i = 0; i < nl.getLength(); i++) { if (nl.item(i) instanceof DocumentType) { // We cannot import DocumentType's, so we need to manually copy it. doctype = (DocumentType) nl.item(i); } } Document doc; if (doctype != null) { doc = builder.getDOMImplementation().createDocument(orig.getDocumentElement().getNamespaceURI(), orig.getDocumentElement().getTagName(), builder.getDOMImplementation().createDocumentType(orig.getDoctype().getName(), orig.getDoctype().getPublicId(), orig.getDoctype().getSystemId())); // XXX what about entity decls inside the DOCTYPE? doc.removeChild(doc.getDocumentElement()); } else { doc = builder.newDocument(); } for (int i = 0; i < nl.getLength(); i++) { Node node = nl.item(i); if (!(node instanceof DocumentType)) { try { doc.appendChild(doc.importNode(node, true)); } catch (DOMException x) { // Thrown in NB-Core-Build #2896 & 2898 inside GeneratedFilesHelper.applyBuildExtensions throw new IOException("Could not import or append " + node + " of " + node.getClass(), x); } } } doc.normalize(); nl = doc.getElementsByTagName("*"); // NOI18N for (int i = 0; i < nl.getLength(); i++) { Element e = (Element) nl.item(i); removeXmlBase(e); NodeList nl2 = e.getChildNodes(); for (int j = 0; j < nl2.getLength(); j++) { Node n = nl2.item(j); if (n instanceof Text && ((Text) n).getNodeValue().trim().length() == 0) { e.removeChild(n); j--; // since list is dynamic } } } return doc; }
From source file:com.omertron.thetvdbapi.tools.TvdbParser.java
/** * Get a list of updates from the URL/*from w w w . j a v a2 s.co m*/ * * @param urlString * @return */ public static TVDBUpdates getUpdates(String urlString) { TVDBUpdates updates = new TVDBUpdates(); Document doc; try { doc = DOMHelper.getEventDocFromUrl(urlString); } catch (WebServiceException ex) { LOG.trace(ERROR_GET_XML, ex); return updates; } if (doc != null) { Node root = doc.getChildNodes().item(0); List<SeriesUpdate> seriesUpdates = new ArrayList<SeriesUpdate>(); List<EpisodeUpdate> episodeUpdates = new ArrayList<EpisodeUpdate>(); List<BannerUpdate> bannerUpdates = new ArrayList<BannerUpdate>(); NodeList updateNodes = root.getChildNodes(); Node updateNode; for (int i = 0; i < updateNodes.getLength(); i++) { updateNode = updateNodes.item(i); if (updateNode.getNodeName().equals(SERIES)) { seriesUpdates.add(parseNextSeriesUpdate((Element) updateNode)); } else if (updateNode.getNodeName().equals(EPISODE)) { episodeUpdates.add(parseNextEpisodeUpdate((Element) updateNode)); } else if (updateNode.getNodeName().equals(BANNER)) { bannerUpdates.add(parseNextBannerUpdate((Element) updateNode)); } } updates.setTime(DOMHelper.getValueFromElement((Element) root, TIME)); updates.setSeriesUpdates(seriesUpdates); updates.setEpisodeUpdates(episodeUpdates); updates.setBannerUpdates(bannerUpdates); } return updates; }
From source file:cz.mzk.editor.server.fedora.utils.FedoraUtils.java
/** * @param foxmlDocument/*from w ww . java 2 s .co m*/ * @param streamToModify * @param newContent */ private static void modifyStream(Document foxmlDocument, String streamToModify, String newContent) { if (newContent != null) { try { Element versionElement = foxmlDocument.createElement("foxml:datastreamVersion"); if (streamToModify.equals(RELS_EXT.getValue())) { versionElement.setAttribute("LABEL", "RDF Statements about this object"); versionElement.setAttribute("FORMAT_URI", RELS_EXT_NAMESPACE_URI); versionElement.setAttribute("MIMETYPE", "application/rdf+xml"); } else { versionElement.setAttribute("MIMETYPE", "text/xml"); if (streamToModify.equals(DC.getValue())) { versionElement.setAttribute("LABEL", "Dublin Core Record for this object"); versionElement.setAttribute("FORMAT_URI", OAI_DC_NAMESPACE_URI); } else if (streamToModify.equals(BIBLIO_MODS.getValue())) { versionElement.setAttribute("LABEL", "BIBLIO_MODS description of current object"); versionElement.setAttribute("FORMAT_URI", BIBILO_MODS_URI); } else if (streamToModify.equals(TEXT_OCR.getValue())) { versionElement.setAttribute("LABEL", ""); Element contLocElement = foxmlDocument.createElement("foxml:contentLocation"); contLocElement.setAttribute("TYPE", "INTERNAL_ID"); contLocElement.setAttribute("REF", "LOCAL"); Element localContElement = foxmlDocument.createElement("foxml:content"); localContElement.setTextContent(newContent); contLocElement.appendChild(localContElement); versionElement.appendChild(contLocElement); } } String lastStreamXPath = "//foxml:datastream[@ID=\'" + streamToModify + "\']/foxml:datastreamVersion[last()]"; Element element = FoxmlUtils.getElement(foxmlDocument, lastStreamXPath); int versionNumber = 0; if (element != null) { versionNumber = getVersionNumber(element.getAttribute("ID")); } versionElement.setAttribute("ID", streamToModify + "." + (versionNumber + 1)); versionElement.setAttribute("CREATED", "NOT YET"); versionElement.setAttribute("SIZE", "0"); Element contentElement = foxmlDocument.createElement("foxml:xmlContent"); try { InputStream is = new ByteArrayInputStream(newContent.getBytes("UTF-8")); Document newStreamDocument = FoxmlUtils.getFoxmlDocument(is); NodeList streamNodeList = newStreamDocument.getChildNodes(); for (int i = 0; i < streamNodeList.getLength(); i++) { Node myNewNode = foxmlDocument.importNode(streamNodeList.item(i), true); contentElement.appendChild(myNewNode); } } catch (IOException e) { System.err.println("IO fauilure" + e); } versionElement.appendChild(contentElement); String streamXPath = "//foxml:datastream[@ID=\'" + streamToModify + "\']"; Element parentOfStream = FoxmlUtils.getElement(foxmlDocument, streamXPath); if (parentOfStream == null) { String digObjXPath = "//foxml:digitalObject"; Element digObjElement = FoxmlUtils.getElement(foxmlDocument, digObjXPath); parentOfStream = foxmlDocument.createElement("datastream"); parentOfStream.setAttribute("ID", streamToModify); parentOfStream.setAttribute("STATE", "A"); //TODO for other streams if necessary if (streamToModify.equals(TEXT_OCR.getValue())) parentOfStream.setAttribute("CONTROL_GROUP", "M"); parentOfStream.setAttribute("VERSIONABLE", "false"); digObjElement.appendChild(parentOfStream); } parentOfStream.appendChild(versionElement); } catch (XPathExpressionException e) { LOGGER.warn("XPath failure", e); } } }
From source file:io.wcm.devops.conga.generator.plugins.fileheader.XmlFileHeader.java
@Override public FileHeaderContext extract(FileContext file) { try {//w ww . j av a2 s .co m Document doc = documentBuilder.parse(file.getFile()); if (doc.getChildNodes().getLength() > 0) { Node firstNode = doc.getChildNodes().item(0); if (firstNode instanceof Comment) { String comment = StringUtils.trim(((Comment) firstNode).getTextContent()); List<String> lines = ImmutableList.copyOf(StringUtils.split(comment, "\n")); return new FileHeaderContext().commentLines(lines); } } } catch (SAXException | IOException ex) { throw new GeneratorException("Unable to parse file header from " + FileUtil.getCanonicalPath(file), ex); } return null; }
From source file:FeatureExtraction.FeatureExtractorOOXMLStructuralPaths.java
/** * Add structural paths from the given xml file into the local map * * @param xmlFilePath the path of a xml file * @param structuralPaths the Map to add the extracted features to *//*from ww w. j av a 2s. c o m*/ private void AddXMLStructuralPaths(InputStream xmlFilePath, String path, Map<String, Integer> structuralPaths) { try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document xml = db.parse(xmlFilePath); NodeList nodeList = xml.getChildNodes(); for (int i = 0; i < nodeList.getLength(); i++) { AddXMLStructuralPathsRecursively(nodeList.item(i), path, structuralPaths); } } catch (Exception ex) { //Console.Print_To_Console(String.format("Error traversing XML file: '%s'", xmlFilePath), true, false); } }
From source file:FeatureExtraction.FeatureExtractorOOXMLStructuralPathsDisk.java
/** * Add structural paths from the given xml file into the local map * * @param xmlFilePath the path of a xml file * @param structuralPaths the Map to add the extracted features to *//*from w w w . ja v a 2 s. c o m*/ private void AddXMLStructuralPaths(String xmlFilePath, Map<String, Integer> structuralPaths) { try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document xml = db.parse(xmlFilePath); NodeList nodeList = xml.getChildNodes(); for (int i = 0; i < nodeList.getLength(); i++) { AddXMLStructuralPathsRecursively(nodeList.item(i), xmlFilePath, structuralPaths); } } catch (Exception ex) { //Console.PrintLine(String.format("Error traversing XML file: '%s'", xmlFilePath), true, false); } }
From source file:eu.domibus.common.util.xmladapter.ToStringAdapter.java
private Node stringToNode(String content) { try {/*w w w . j a va 2 s. c o m*/ Document doc = this.documentBuilderFactory.newDocumentBuilder() .parse(new InputSource(new StringReader(content))); if (doc.getChildNodes().getLength() == 1) { return doc.getChildNodes().item(1); } } catch (SAXException | IOException | ParserConfigurationException e) { ToStringAdapter.LOG.warn("Error during transformation of String to Node", e); return null; } return null; }
From source file:com.espirit.moddev.examples.uxbridge.newswidget.test.MongoCommandITCaseWithoutMongo.java
/** * Test add./*from ww w . j a va 2 s .com*/ * * @throws Exception the exception */ @Test public void testAdd() throws Exception { template.sendBody("jms:topic:BUS_OUT", getContent("src/test/resources/inbox/add/pressreleasesdetails_128.xml", "mongodbsimple")); Thread.sleep(7000); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); StringReader inStream = new StringReader(errorMessage); InputSource inSource = new InputSource(inStream); Document doc = dBuilder.parse(inSource); doc.getDocumentElement().normalize(); NamedNodeMap nMap = doc.getChildNodes().item(0).getAttributes(); assertEquals("response message is wrong", "uxb_entity", doc.getChildNodes().item(0).getNodeName()); }
From source file:com.eucalyptus.objectstorage.pipeline.WalrusSoapUserAuthenticationHandler.java
public void handle(MappingHttpRequest httpRequest, Document doc) throws AuthenticationException { NodeList childNodes = doc.getChildNodes(); Element bodyElem = doc.getDocumentElement(); Node operationElem = bodyElem.getFirstChild(); String operationName = operationElem.getNodeName(); if (operationName.length() > 0) { NodeList authNodes = operationElem.getChildNodes(); String queryId = null, timestamp = null, signature = null; for (int i = 0; i < authNodes.getLength(); ++i) { Node node = authNodes.item(i); if (node.getNodeName().equals(WalrusProperties.RequiredSOAPTags.AWSAccessKeyId.toString())) { queryId = node.getFirstChild().getNodeValue().trim(); } else if (node.getNodeName().equals(WalrusProperties.RequiredSOAPTags.Timestamp.toString())) { timestamp = node.getFirstChild().getNodeValue().trim(); } else if (node.getNodeName().equals(WalrusProperties.RequiredSOAPTags.Signature.toString())) { signature = node.getFirstChild().getNodeValue().trim(); }/*from ww w . j ava 2 s . co m*/ } if (queryId == null) throw new AuthenticationException("Unable to parse access key id"); if (signature == null) throw new AuthenticationException("Unable to parse signature"); if (timestamp == null) throw new AuthenticationException("Unable to parse timestamp"); //check timestamp verifyTimestamp(timestamp); String data = "AmazonS3" + operationName + timestamp; //check signature authenticate(httpRequest, queryId, signature, data); } else { throw new AuthenticationException("Invalid operation specified"); } }