private void parsePlanet(Element planetElement, Planet planet) { List<Satellite> satellitesList = new ArrayList<>(); NodeList satellites = planetElement.getElementsByTagName("satellites"); if (satellites.getLength() > 0) { satellites = satellites.item(0).getChildNodes(); for (int i = 0; i < satellites.getLength(); i++) { if (satellites.item(i).getNodeType() != Node.ELEMENT_NODE) { continue; } Satellite satellite = null; Element satelliteElement = (Element) satellites.item(i); if (satelliteElement.getNodeName().equals("satellite")) { satellite = new Satellite(); parseSatellite(satelliteElement, satellite); } else if (satelliteElement.getNodeName().equals("artificial")) { satellite = new ArtificialSatellite(); parseArtificial(satelliteElement, (ArtificialSatellite) satellite); } else if (satelliteElement.getNodeName().equals("ion_cannon")) { satellite = new IonCannon(); parseIonCannon(satelliteElement, (IonCannon) satellite); } else if (satelliteElement.getNodeName().equals("station")) { satellite = new SpaceStation(); parseStation(satelliteElement, (SpaceStation) satellite); } satellitesList.add(satellite); } planet.setSatellites(satellitesList); } parseBody(planetElement, planet); }
@Test public void testFieldHasMatchingUserValues() throws Exception { LOG.info("testFieldHasMatchingUserValues"); DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder(); XPath xpath = XPathFactory.newInstance().newXPath(); Document doc = db.parse(this.getClass().getResourceAsStream(SAMPLE_EDOC_XML)); // enumerate all fields final String fieldDefs = "/edlContent/edl/field/display/values"; NodeList nodes = (NodeList) xpath.evaluate(fieldDefs, doc, XPathConstants.NODESET); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); String name = (String) xpath.evaluate("../../@name", node, XPathConstants.STRING); LOG.debug("Name: " + name); LOG.debug("Value: " + node.getFirstChild().getNodeValue()); final String expr = "/edlContent/data/version[@current='true']/fieldEntry[@name=current()/../../@name and value=current()]"; NodeList matchingUserValues = (NodeList) xpath.evaluate(expr, node, XPathConstants.NODESET); LOG.debug(matchingUserValues + ""); LOG.debug(matchingUserValues.getLength() + ""); if ("gender".equals(name)) { assertTrue("Matching values > 0", matchingUserValues.getLength() > 0); } for (int j = 0; j < matchingUserValues.getLength(); j++) { LOG.debug(matchingUserValues.item(j).getFirstChild().getNodeValue()); } } }
private void loadDecoratorMappers(NodeList nodes) { clearDecoratorMappers(); Properties emptyProps = new Properties(); pushDecoratorMapper("com.opensymphony.module.sitemesh.mapper.NullDecoratorMapper", emptyProps); // note, this works from the bottom node up. for (int i = nodes.getLength() - 1; i > 0; i--) { if (nodes.item(i) instanceof Element) { Element curr = (Element) nodes.item(i); if ("mapper".equalsIgnoreCase(curr.getTagName())) { String className = curr.getAttribute("class"); Properties props = new Properties(); // build properties from <param> tags. NodeList children = curr.getChildNodes(); for (int j = 0; j < children.getLength(); j++) { if (children.item(j) instanceof Element) { Element currC = (Element) children.item(j); if ("param".equalsIgnoreCase(currC.getTagName())) { String value = currC.getAttribute("value"); props.put(currC.getAttribute("name"), replaceProperties(value)); } } } // add mapper pushDecoratorMapper(className, props); } } } pushDecoratorMapper( "com.opensymphony.module.sitemesh.mapper.InlineDecoratorMapper", emptyProps); }
public ArrayList<String> parseXML() throws Exception { ArrayList<String> ret = new ArrayList<String>(); handshake(); URL url = new URL( "http://mangaonweb.com/page.do?cdn=" + cdn + "&cpn=book.xml&crcod=" + crcod + "&rid=" + (int) (Math.random() * 10000)); String page = DownloaderUtils.getPage(url.toString(), "UTF-8", cookies); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); InputSource is = new InputSource(new StringReader(page)); Document d = builder.parse(is); Element doc = d.getDocumentElement(); NodeList pages = doc.getElementsByTagName("page"); total = pages.getLength(); for (int i = 0; i < pages.getLength(); i++) { Element e = (Element) pages.item(i); ret.add(e.getAttribute("path")); } return (ret); }
public void init(String path) { XmlParser parser = new XmlParser(context); Document doc = parser.getDomElement(path); Log.d("debugMarcherList", "Got parser and created got the doc"); Log.d("debugMarcherList", "" + doc); // NodeList id = doc.getElementsByTagName(ID); // Element el = ( Element ) id.item( 0 ); // iden = parser.getElementValue(el); NodeList nl = doc.getElementsByTagName(DOT); Log.d("debugMarcherList", "Got the node list"); Log.d("debugMarcherList", "" + nl.getLength()); for (int i = 0; i < nl.getLength(); i++) { Element e = (Element) nl.item(i); RawDot dot = new RawDot(); dot.setBpm(Integer.parseInt(parser.getValue(e, BPM))); dot.setCount(Integer.parseInt(parser.getValue(e, SETCOUNT))); dot.setSide(Integer.parseInt(parser.getValue(e, SIDE))); dot.setHorizontal(Integer.parseInt(parser.getValue(e, HORIZONTAL))); dot.setHorizontalDirection(parser.getValue(e, HORIZONTALDIRECTION)); dot.setHorizontalStep(Integer.parseInt(parser.getValue(e, HORIZONTALSTEP))); dot.setVertical(parser.getValue(e, VERTICAL)); dot.setVerticalDir(parser.getValue(e, VERTICALDIRECTION)); dot.setVerticalStep(Integer.parseInt(parser.getValue(e, VERTICALSTEP))); // dotBook.add(dot); Log.d("debugMarcherList", "" + dotBook.size()); Log.d("DotBook", "BPM: " + i + " " + dot.getBPM()); Log.d("DotBook", "SetCount: " + i + " " + dot.getSetCount()); } Log.d("debugMarcherList", "Done with the init"); }
public void delete() throws ParserConfigurationException, SAXException, IOException, TransformerException { Document document = new GetDocument().getDocument(); Element rootElement = document.getDocumentElement(); NodeList contacts = rootElement.getChildNodes(); System.out.println("Enter the name of the contact to delete: "); BufferedReader inItem = new BufferedReader(new InputStreamReader(System.in)); String contactToDelete = inItem.readLine(); boolean isContactFound = false; for (int i = 0; i < contacts.getLength(); i++) { Node contact = contacts.item(i); NodeList contactData = contact.getChildNodes(); for (int j = 0; j < contactData.getLength(); j++) { Node dataNode = contactData.item(j); if (dataNode.getNodeName().equals("name") && dataNode.getTextContent().equals(contactToDelete)) { contact.getParentNode().removeChild(contact); isContactFound = true; System.out.println("The contact " + contactToDelete + " has been deleted."); } } } Transform.transform(document); if (!isContactFound) System.out.println("No such contact found."); }
public VOMSWarningMessage[] warningMessages() { NodeList nodes = xmlResponse.getElementsByTagName("item"); if (nodes.getLength() == 0) return null; List<VOMSWarningMessage> warningList = new ArrayList<VOMSWarningMessage>(); for (int i = 0; i < nodes.getLength(); i++) { Element itemElement = (Element) nodes.item(i); Element numberElement = (Element) itemElement.getElementsByTagName("number").item(0); Element messageElement = (Element) itemElement.getElementsByTagName("message").item(0); int number = Integer.parseInt(numberElement.getFirstChild().getNodeValue()); if (number < ERROR_OFFSET) warningList.add( new VOMSWarningMessage(number, messageElement.getFirstChild().getNodeValue())); } if (warningList.isEmpty()) return null; return warningList.toArray(new VOMSWarningMessage[warningList.size()]); }
private void configure() { NodeList PEPList; Node pepNode; User2PEPs = new Hashtable<String, Vector<PEP>>(); pepVect = new Vector<PEP>(); PEPList = config.getDocumentElement().getElementsByTagName("PEP"); int NumOfPEPS = PEPList.getLength(); pepVect = new Vector<PEP>(NumOfPEPS); for (int i = 0; i < NumOfPEPS; i++) { pepNode = PEPList.item(i); String ip = pepNode.getAttributes().getNamedItem("ip").getNodeValue(); String domain = pepNode.getAttributes().getNamedItem("domain").getNodeValue(); long upbw = Long.parseLong(pepNode.getAttributes().getNamedItem("upbw").getNodeValue()); long dobw = Long.parseLong(pepNode.getAttributes().getNamedItem("dobw").getNodeValue()); PEP pep = new PEP(ip, domain, upbw, dobw); pepVect.add(pep); NodeList userList = pepNode.getChildNodes(); for (int j = 0; j < userList.getLength(); j++) { Node userNode = userList.item(j); if (userNode.getNodeName() == "User") { String userIP = userNode.getAttributes().getNamedItem("ip").getNodeValue(); Vector<PEP> up = User2PEPs.get(userIP); if (up == null) { up = new Vector<PEP>(1); } up.add(pep); User2PEPs.put(userIP, up); } } } }
private ArrayList<HashMap<String, String>> parseXMLResponse(String response) { ArrayList<HashMap<String, String>> result = new ArrayList<HashMap<String, String>>(); if (response == null || response.equals("")) return result; try { response = response.substring("<?xml version=\"1.0\" encoding=\"UTF-8\"?>".length() + 2); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document dom = builder.parse(new InputSource(new StringReader(response))); Element root = dom.getDocumentElement(); NodeList platformsList = root.getElementsByTagName("P"); if (platformsList != null && platformsList.getLength() > 0) { for (int i = 0; i < platformsList.getLength(); i++) { Node platform = platformsList.item(i); String nameString = platform.getNodeName(); if (!nameString.equalsIgnoreCase("P")) continue; Node dirNode = platform.getAttributes().getNamedItem("N"); String direction = dirNode.getTextContent(); NodeList trainsList = platform.getChildNodes(); for (HashMap<String, String> train : getTrains(trainsList)) { train.put("platform", direction); result.add(train); } } } } catch (Exception e) { // This should never happen Log.w("DeparturesFetcher", e); } return result; }
private void parseDocumentTra() { // get the root element Element docEle = readedDocument.getDocumentElement(); // Get all rules NodeList rules = docEle.getElementsByTagName("rule"); //// System.out.println(rules.getLength()); ArrayList<String> itemsetAntecedents = new ArrayList(); ArrayList<String> itemsetConsequents = new ArrayList(); if (rules != null && rules.getLength() > 0) { for (int i = 0; i < rules.getLength(); i++) { // Get rule number i Element rule = (Element) rules.item(i); itemsetAntecedents = processAntecedents(rule); itemsetConsequents = processConsequents(rule); processItemset(itemsetAntecedents, itemsetConsequents); processRule(itemsetAntecedents, itemsetConsequents); } } //// System.out.println(items.toString()); //// System.out.println(itemsets.toString()); }
private ArrayList processConsequents(Element rule) { NodeList antecedents = rule.getElementsByTagName("consequents"); ArrayList<String> itemset = new ArrayList(); if (antecedents != null && antecedents.getLength() > 0) { Element antecedent = (Element) antecedents.item(0); // Get attributes (items) NodeList attributes = antecedent.getElementsByTagName("attribute"); if (attributes != null && attributes.getLength() > 0) { for (int i = 0; i < attributes.getLength(); i++) { Element attr = (Element) attributes.item(i); String itemId = attr.getAttribute("name") + itemNameValueSeparator + attr.getAttribute("value"); if (!items.containsKey(itemId)) { items.put(itemId, itemCounter); itemCounter++; } // Save item to generate itemsets after.. itemset.add(itemId); } } } return itemset; }
// utility method to create or get an existing use-sdk xml element under manifest. // this could be made more generic by adding more metadata to the enum but since there is // only one case so far, keep it simple. private static XmlElement createOrGetUseSdk( ActionRecorder actionRecorder, XmlDocument document) { Element manifest = document.getXml().getDocumentElement(); NodeList usesSdks = manifest.getElementsByTagName(ManifestModel.NodeTypes.USES_SDK.toXmlName()); if (usesSdks.getLength() == 0) { usesSdks = manifest.getElementsByTagNameNS( SdkConstants.ANDROID_URI, ManifestModel.NodeTypes.USES_SDK.toXmlName()); } if (usesSdks.getLength() == 0) { // create it first. Element useSdk = manifest.getOwnerDocument().createElement(ManifestModel.NodeTypes.USES_SDK.toXmlName()); manifest.appendChild(useSdk); XmlElement xmlElement = new XmlElement(useSdk, document); Actions.NodeRecord nodeRecord = new Actions.NodeRecord( Actions.ActionType.INJECTED, new Actions.ActionLocation(xmlElement.getSourceLocation(), PositionImpl.UNKNOWN), xmlElement.getId(), "use-sdk injection requested", NodeOperationType.STRICT); actionRecorder.recordNodeAction(xmlElement, nodeRecord); return xmlElement; } else { return new XmlElement((Element) usesSdks.item(0), document); } }
public void hydrateAction(MutableAction action, Node actionNode) { NodeList actionNodeChildren = actionNode.getChildNodes(); for (int i = 0; i < actionNodeChildren.getLength(); i++) { Node actionNodeChild = actionNodeChildren.item(i); if (actionNodeChild.getNodeType() != Node.ELEMENT_NODE) continue; if (ELEMENT.name.equals(actionNodeChild)) { action.name = XMLUtil.getTextContent(actionNodeChild); } else if (ELEMENT.argumentList.equals(actionNodeChild)) { NodeList argumentChildren = actionNodeChild.getChildNodes(); for (int j = 0; j < argumentChildren.getLength(); j++) { Node argumentChild = argumentChildren.item(j); if (argumentChild.getNodeType() != Node.ELEMENT_NODE) continue; MutableActionArgument actionArgument = new MutableActionArgument(); hydrateActionArgument(actionArgument, argumentChild); action.arguments.add(actionArgument); } } } }
private void MontaDadosDataTable() throws ParserConfigurationException, SAXException, IOException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(this.arquivoXML.getInputstream()); Element element = (Element) doc.getDocumentElement(); NodeList nodes = ((Node) element).getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { System.out.println(nodes.item(0).getAttributes().getNamedItem("NOME-COMPLETO")); NodeList nodesItem = nodes.item(i).getChildNodes(); this.researcher = null; if (nodesItem.getLength() > 0) this.researcher = new Researcher(); this.researcher.setResearcherName( nodes.item(0).getAttributes().getNamedItem("NOME-COMPLETO").getTextContent()); for (int j = 0; j < nodesItem.getLength(); j++) { // if(nodesItem.item(j).getNodeName().equals("DADOS-GERAIS")) // this.researcher.setResearcherName(nodesItem.item(j).getTextContent()); } if (this.researcher != null) this.l_researcher.add(this.researcher); } }
private void DisplayUserSelect() { if (UserAcountModel.getInstance().getDocument() == null) return; NodeList nodeList = UserAcountModel.getInstance().getDocument().getElementsByTagName("user"); userSelect = new Button[nodeList.getLength()]; for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { NamedNodeMap attributes = node.getAttributes(); Button select = new Button(this); TextView text = new TextView(this); select.setTag(attributes.getNamedItem("id").getTextContent()); text.setText( attributes.getNamedItem("firstname").getTextContent() + " " + attributes.getNamedItem("lastname").getTextContent() + ": " + attributes.getNamedItem("username").getTextContent()); select.setText(attributes.getNamedItem("id").getTextContent()); userSelect[i] = select; LinearLayout llSelectUser = (LinearLayout) findViewById(R.id.llSelectUsers); llSelectUser.addView(text); llSelectUser.addView(userSelect[i]); userSelect[i].setOnClickListener(handleOnClick(userSelect[i])); } } }
/** Loads info from xml that is supplied as an argument to the internal data objects. */ public void loadXML(final String xml) { final Document document = getXMLDocument(xml); if (document == null) { return; } /* get root <drbdgui> */ final Node rootNode = getChildNode(document, "drbdgui"); final Map<String, List<Host>> hostMap = new LinkedHashMap<String, List<Host>>(); if (rootNode != null) { /* download area */ final String downloadUser = getAttribute(rootNode, DOWNLOAD_USER_ATTR); final String downloadPasswd = getAttribute(rootNode, DOWNLOAD_PASSWD_ATTR); if (downloadUser != null && downloadPasswd != null) { Tools.getConfigData().setDownloadLogin(downloadUser, downloadPasswd, true); } /* hosts */ final Node hostsNode = getChildNode(rootNode, "hosts"); if (hostsNode != null) { final NodeList hosts = hostsNode.getChildNodes(); if (hosts != null) { for (int i = 0; i < hosts.getLength(); i++) { final Node hostNode = hosts.item(i); if (hostNode.getNodeName().equals(HOST_NODE_STRING)) { final String nodeName = getAttribute(hostNode, HOST_NAME_ATTR); final String sshPort = getAttribute(hostNode, HOST_SSHPORT_ATTR); final String color = getAttribute(hostNode, HOST_COLOR_ATTR); final String useSudo = getAttribute(hostNode, HOST_USESUDO_ATTR); final Node ipNode = getChildNode(hostNode, "ip"); String ip = null; if (ipNode != null) { ip = getText(ipNode); } final Node usernameNode = getChildNode(hostNode, "user"); final String username = getText(usernameNode); setHost( hostMap, username, nodeName, ip, sshPort, color, "true".equals(useSudo), true); } } } } /* clusters */ final Node clustersNode = getChildNode(rootNode, "clusters"); if (clustersNode != null) { final NodeList clusters = clustersNode.getChildNodes(); if (clusters != null) { for (int i = 0; i < clusters.getLength(); i++) { final Node clusterNode = clusters.item(i); if (clusterNode.getNodeName().equals("cluster")) { final String clusterName = getAttribute(clusterNode, CLUSTER_NAME_ATTR); final Cluster cluster = new Cluster(); cluster.setName(clusterName); Tools.getConfigData().addClusterToClusters(cluster); loadClusterHosts(clusterNode, cluster, hostMap); } } } } } }
private void xmlReadSelectedElements(JarPackageData jarPackage, Element element) throws java.io.IOException { if (element.getNodeName().equals("selectedElements")) { // $NON-NLS-1$ jarPackage.setExportClassFiles( getBooleanAttribute(element, "exportClassFiles")); // $NON-NLS-1$ jarPackage.setExportOutputFolders( getBooleanAttribute(element, "exportOutputFolder", false)); // $NON-NLS-1$ jarPackage.setExportJavaFiles(getBooleanAttribute(element, "exportJavaFiles")); // $NON-NLS-1$ NodeList selectedElements = element.getChildNodes(); Set<IAdaptable> elementsToExport = new HashSet<IAdaptable>(selectedElements.getLength()); for (int j = 0; j < selectedElements.getLength(); j++) { Node selectedNode = selectedElements.item(j); if (selectedNode.getNodeType() != Node.ELEMENT_NODE) continue; Element selectedElement = (Element) selectedNode; if (selectedElement.getNodeName().equals("file")) // $NON-NLS-1$ addFile(elementsToExport, selectedElement); else if (selectedElement.getNodeName().equals("folder")) // $NON-NLS-1$ addFolder(elementsToExport, selectedElement); else if (selectedElement.getNodeName().equals("project")) // $NON-NLS-1$ addProject(elementsToExport, selectedElement); else if (selectedElement.getNodeName().equals("javaElement")) // $NON-NLS-1$ addJavaElement(elementsToExport, selectedElement); // Note: Other file types are not handled by this writer } jarPackage.setElements(elementsToExport.toArray()); } }
public void parserXml(String fileName) { try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document document = db.parse(fileName); NodeList employees = document.getChildNodes(); for (int i = 0; i < employees.getLength(); i++) { Node employee = employees.item(i); NodeList employeeInfo = employee.getChildNodes(); for (int j = 0; j < employeeInfo.getLength(); j++) { Node node = employeeInfo.item(j); NodeList employeeMeta = node.getChildNodes(); for (int k = 0; k < employeeMeta.getLength(); k++) { System.out.println( employeeMeta.item(k).getNodeName() + ":" + employeeMeta.item(k).getTextContent()); } } } System.out.println("解析完毕"); } catch (FileNotFoundException e) { System.out.println(e.getMessage()); } catch (ParserConfigurationException e) { System.out.println(e.getMessage()); } catch (SAXException e) { System.out.println(e.getMessage()); } catch (IOException e) { System.out.println(e.getMessage()); } }
private static List<Element> getTopLevelElementChildren( Element element, String parentName, String childrenName) throws TikaException { Node parentNode = null; if (parentName != null) { // Should be only zero or one <parsers> / <detectors> etc tag NodeList nodes = element.getElementsByTagName(parentName); if (nodes.getLength() > 1) { throw new TikaException("Properties may not contain multiple " + parentName + " entries"); } else if (nodes.getLength() == 1) { parentNode = nodes.item(0); } } else { // All children directly on the master element parentNode = element; } if (parentNode != null) { // Find only the direct child parser/detector objects NodeList nodes = parentNode.getChildNodes(); List<Element> elements = new ArrayList<Element>(); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); if (node instanceof Element) { Element nodeE = (Element) node; if (childrenName.equals(nodeE.getTagName())) { elements.add(nodeE); } } } return elements; } else { // No elements of this type return Collections.emptyList(); } }
private void parseEvents(Element element) throws NumberFormatException, IOException { NodeList nodeListGpsUpdates = element.getElementsByTagName("GpsUpdate"); if ((nodeListGpsUpdates != null) && (nodeListGpsUpdates.getLength() > 0)) { for (int i = 0; i < nodeListGpsUpdates.getLength(); i++) { Element e = (Element) nodeListGpsUpdates.item(i); EventNodeGps eventNodeGps = this.getEventNodeGps(e); this.events.add(eventNodeGps); } } NodeList nodeListMagnetometerUpdates = element.getElementsByTagName("MagnetometerUpdate"); if ((nodeListMagnetometerUpdates != null) && (nodeListMagnetometerUpdates.getLength() > 0)) { for (int i = 0; i < nodeListMagnetometerUpdates.getLength(); i++) { Element e = (Element) nodeListMagnetometerUpdates.item(i); EventNodeMagnetometer eventNodeMagnetometer = this.getEventNodeMagnetometer(e); this.events.add(eventNodeMagnetometer); } } }
protected void load(Element root) throws Exception { NodeList list; int i; list = WSHelper.getElementChildren(root, "Messages"); if (list != null) { for (i = 0; i < list.getLength(); i++) { Element nc = (Element) list.item(i); _Messages.addElement(JanusMessageInfo.loadFrom(nc)); } } list = WSHelper.getElementChildren(root, "Rating"); if (list != null) { for (i = 0; i < list.getLength(); i++) { Element nc = (Element) list.item(i); _Rating.addElement(JanusRatingInfo.loadFrom(nc)); } } list = WSHelper.getElementChildren(root, "Moderate"); if (list != null) { for (i = 0; i < list.getLength(); i++) { Element nc = (Element) list.item(i); _Moderate.addElement(JanusModerateInfo.loadFrom(nc)); } } }
private Item parseItem(Element element) { Item item = new Item(); NodeList items = element.getElementsByTagName(Item.LABEL_TITLE); if (null != items && items.getLength() > 0) { item.title = items.item(0).getTextContent(); } items = element.getElementsByTagName(Item.LABEL_DESCRIPTION); if (null != items && items.getLength() > 0) { item.description = items.item(0).getTextContent(); } items = element.getElementsByTagName(Item.LABEL_LINK); if (null != items && items.getLength() > 0) { item.link = items.item(0).getTextContent(); } items = element.getElementsByTagName(Item.LABEL_PUBDATE); if (null != items && items.getLength() > 0) { item.pubDate = items.item(0).getTextContent(); } items = element.getElementsByTagName(Guid.LABEL_GUID); if (null != items && items.getLength() > 0) { item.guid = new Guid(); String value = items.item(0).getAttributes().getNamedItem(Guid.LABEL_ISPERMALINK).getTextContent(); item.guid.isPermaLink = Boolean.parseBoolean(value); item.guid.url = items.item(0).getTextContent(); } return item; }
private void parseReporting(Element configRoot, LocalBenchmark localBenchmark) { Element reportsEl = (Element) configRoot.getElementsByTagName("reports").item(0); NodeList reportElList = reportsEl.getElementsByTagName("report"); for (int i = 0; i < reportElList.getLength(); i++) { if (reportElList.item(i) instanceof Element) { ReportDesc reportDesc = new ReportDesc(); Element thisReportEl = (Element) reportElList.item(i); if (thisReportEl.getAttribute("includeAll") != null) { String inclAll = ConfigHelper.getStrAttribute(thisReportEl, "includeAll"); if (inclAll.equalsIgnoreCase("true")) { reportDesc.setIncludeAll(true); reportDesc.addReportItems(all); localBenchmark.addReportDesc(reportDesc); reportDesc.setReportName(ConfigHelper.getStrAttribute(thisReportEl, "name")); continue; } } NodeList itemsEl = thisReportEl.getElementsByTagName("item"); for (int j = 0; j < itemsEl.getLength(); j++) { Element itemEl = (Element) itemsEl.item(j); String productName = ConfigHelper.getStrAttribute(itemEl, "product"); String productConfig = ConfigHelper.getStrAttribute(itemEl, "config"); reportDesc.addReportItem(productName, productConfig); } reportDesc.setReportName(ConfigHelper.getStrAttribute(thisReportEl, "name")); localBenchmark.addReportDesc(reportDesc); } } }
public void processXMLDelete(String content) throws ClientProtocolException, IOException { try { // Log.i(TAG,"Content =" + content); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(new InputSource(new StringReader(content))); doc.getDocumentElement().normalize(); NodeList nodeList = doc.getElementsByTagName("results"); /** Assign String array length by arraylist size */ succeed = new String[nodeList.getLength()]; for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); Element fstElmnt = (Element) node; NodeList succeedList = fstElmnt.getElementsByTagName("succeed"); Element succeedElement = (Element) succeedList.item(0); succeedList = succeedElement.getChildNodes(); succeed[i] = ((Node) succeedList.item(0)).getNodeValue(); } } catch (Exception e) { System.out.println("XML Pasing Excpetion = " + e); } }
/** * Test adding a second md-record to ContentRelation. One md-record already exists. * * @throws Exception Thrown if adding one md-record failed. */ @Test public void testAddMdRecord() throws Exception { // add one more md-record Document relationCreated = getDocument(relationXml); NodeList mdRecordsCreated = selectNodeList(relationCreated, "/content-relation/md-records/md-record"); int numberMdRecordsCreated = mdRecordsCreated.getLength(); Element mdRecord = relationCreated.createElementNS( "http://www.escidoc.de/schemas/metadatarecords/0.5", "escidocMetadataRecords:md-record"); mdRecord.setAttribute("name", "md2"); mdRecord.setAttribute("schema", "bla"); Element mdRecordContent = relationCreated.createElement("md"); mdRecord.appendChild(mdRecordContent); mdRecordContent.setTextContent("bla"); selectSingleNode(relationCreated, "/content-relation/md-records").appendChild(mdRecord); String relationWithNewMdRecord = toString(relationCreated, false); String updatedXml = update(this.relationId, relationWithNewMdRecord); // check updated assertXmlValidContentRelation(updatedXml); Document updatedRelationDocument = getDocument(updatedXml); NodeList mdRecordsUpdated = selectNodeList(updatedRelationDocument, "/content-relation/md-records/md-record"); int numberMdRecordsUpdated = mdRecordsUpdated.getLength(); assertEquals( "the content relation should have one additional" + " md-record after update ", numberMdRecordsUpdated, numberMdRecordsCreated + 1); }
@Override public boolean hasAttribute(Entity entity, String attribute) throws EntityNotFoundException, SchemeException { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder; try { dBuilder = dbFactory.newDocumentBuilder(); Document doc; doc = dBuilder.parse(getURL().openStream()); NodeList nodes = doc.getElementsByTagName("xs:element"); for (int i = 0; i < nodes.getLength(); i++) { Element element = (Element) nodes.item(i); if (element.getAttribute("name").equals(entity.getName())) { NodeList childNodes = element.getElementsByTagName("xs:attribute"); for (int j = 0; j < childNodes.getLength(); j++) { element = (Element) childNodes.item(j); if (element.getAttribute("name").equals(attribute)) { return true; } } } } } catch (Exception e) { throw new SchemeException(e); } throw new EntityNotFoundException(entity.getName()); }
private Map readMap(Element l) { Map map = new HashMap(); NodeList nodes = l.getChildNodes(); Set roles = new HashSet(); for (int i = 0; i < nodes.getLength(); i++) { Node item = nodes.item(i); if (item instanceof Element) { String key = item.getNodeName(); StringBuffer value = new StringBuffer(); NodeList vals = item.getChildNodes(); for (int j = 0; j < vals.getLength(); j++) { Node val = vals.item(j); if (val instanceof Text) { value.append(val.getNodeValue()); } } String val = value.toString(); if (ROLE_ASSIGNMENT.equals(key)) { roles.add(val); } else { map.put(key, val); } } } if (roles.size() != 0) { map.put(ROLE_ASSIGNMENT, roles); } return map; }
@Override public void loadFromSnapshot(Document doc, Element node) { NodeList nl = node.getElementsByTagName("player"); for (int i = 0; i < nl.getLength(); i++) { Element playerEl = (Element) nl.item(i); Player player = game.getPlayer(Integer.parseInt(playerEl.getAttribute("index"))); castles.put(player, Integer.parseInt(playerEl.getAttribute("castles"))); } nl = node.getElementsByTagName("castle"); for (int i = 0; i < nl.getLength(); i++) { Element castleEl = (Element) nl.item(i); Position pos = XMLUtils.extractPosition(castleEl); Location loc = Location.valueOf(castleEl.getAttribute("location")); Castle castle = convertCityToCastle(pos, loc, true); boolean isNew = XMLUtils.attributeBoolValue(castleEl, "new"); boolean isCompleted = XMLUtils.attributeBoolValue(castleEl, "completed"); if (isNew) { newCastles.add(castle); } else if (isCompleted) { emptyCastles.add(castle); } else { scoreableCastleVicinity.put(castle, castle.getVicinity()); } } }
public OptionSelectionDetailsType(Node node) throws XPathExpressionException { XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); Node childNode = null; NodeList nodeList = null; childNode = (Node) xpath.evaluate("OptionSelection", node, XPathConstants.NODE); if (childNode != null && !isWhitespaceNode(childNode)) { this.optionSelection = childNode.getTextContent(); } childNode = (Node) xpath.evaluate("Price", node, XPathConstants.NODE); if (childNode != null && !isWhitespaceNode(childNode)) { this.price = childNode.getTextContent(); } childNode = (Node) xpath.evaluate("OptionType", node, XPathConstants.NODE); if (childNode != null && !isWhitespaceNode(childNode)) { this.optionType = OptionTypeListType.fromValue(childNode.getTextContent()); } nodeList = (NodeList) xpath.evaluate("PaymentPeriod", node, XPathConstants.NODESET); if (nodeList != null && nodeList.getLength() > 0) { for (int i = 0; i < nodeList.getLength(); i++) { Node subNode = nodeList.item(i); this.paymentPeriod.add(new InstallmentDetailsType(subNode)); } } }
/** * Returns the value of the element named <code>propertyName</code> at index <code>index</code>, * where the index starts at 0 (zero). * * @param dom * @param propertyName * @param index * @return */ protected final String getElementValueByQName( final Document dom, final QName propertyName, final int index) { final NodeList elementsByQName = getElementsByQName(dom, propertyName); if (elementsByQName.getLength() == 0) { throw new NoSuchElementException( "No element named " + propertyName + " in " + dom.getDocumentElement().getLocalName()); } if (index > elementsByQName.getLength()) { throw new NoSuchElementException( "Expected element named " + propertyName + " at index " + index + " but there are only " + elementsByQName.getLength() + " elements in the node list"); } final Node item = elementsByQName.item(index); final Node firstChild = item.getFirstChild(); if (null == firstChild) { throw new NullPointerException(propertyName + "[" + index + "] has no content"); } String nodeValue = firstChild.getNodeValue(); return nodeValue; }