public Room buildRoom(Node n_in) { NodeList na = ((Element) n_in).getElementsByTagName("name"); this.name = ((Element) na.item(0)).getTextContent(); NodeList ty = ((Element) n_in).getElementsByTagName("type"); this.type = ((Element) ty.item(0)).getTextContent(); NodeList desc = ((Element) n_in).getElementsByTagName("description"); this.description = ((Element) desc.item(0)).getTextContent(); NodeList bord = ((Element) n_in).getElementsByTagName("border"); for (int i = 0; i < bord.getLength(); i++) { this.border.add(new Border(((Element) bord.item(i)))); } NodeList cont = ((Element) n_in).getElementsByTagName("container"); for (int i = 0; i < cont.getLength(); i++) { this.containers.add(((Element) cont.item(i)).getTextContent()); } NodeList it = ((Element) n_in).getElementsByTagName("item"); for (int i = 0; i < it.getLength(); i++) { this.items.add(((Element) it.item(i)).getTextContent()); } NodeList cr = ((Element) n_in).getElementsByTagName("creature"); for (int i = 0; i < cr.getLength(); i++) { this.creatures.add(((Element) cr.item(i)).getTextContent()); } NodeList trig = ((Element) n_in).getElementsByTagName("trigger"); for (int i = 0; i < trig.getLength(); i++) { Trigger t = new Trigger(trig.item(i)); this.triggers.add(t); if (t.getCondition() != null) { this.status = t.getCondition().getStatus(); } } return this; }
private void addRunConfigurationFromXMLTree(Element treeTop, String runManagerName) { NodeList list = treeTop.getChildNodes(); for (int i = 0; i < list.getLength(); i++) { NamedNodeMap nodeMap = list.item(i).getAttributes(); if (nodeMap != null && nodeMap.getNamedItem("name") != null) { if (!runManagerName.equals(nodeMap.getNamedItem("name").getNodeValue())) { continue; } NodeList configList = list.item(i).getChildNodes(); for (int j = 0; j < configList.getLength(); j++) { NamedNodeMap configNodeMap = configList.item(j).getAttributes(); if (configNodeMap != null && configNodeMap.getNamedItem("default") != null && configNodeMap.getNamedItem("default").getNodeValue() != null && configNodeMap.getNamedItem("default").getNodeValue().equals("false")) { try { runConfigurations.add(new ASIdeaRunConfiguration(configList.item(j))); } catch (ASExternalImporterException e) { // Ignore } } } } } }
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 static IPeakSet<? extends IPeak> parsePeakSet(Node parent) throws XmlParserException { // retrieve all the properties Vector<IPeak> peaks = new Vector<IPeak>(); NodeList nodes = parent.getChildNodes(); for (int nodeid = 0; nodeid < nodes.getLength(); ++nodeid) { Node node = nodes.item(nodeid); if (node.getNodeType() != Node.ELEMENT_NODE) continue; Element element = (Element) node; if (element.getTagName().equals("peaks")) { NodeList nodes2 = node.getChildNodes(); for (int nodeid2 = 0; nodeid2 < nodes2.getLength(); ++nodeid2) { Node node2 = nodes2.item(nodeid2); if (node2.getNodeType() != Node.ELEMENT_NODE) continue; IPeak peak = parseIPeak(node2); if (peak != null) peaks.add(peak); } } } // create the bugger IPeakSet<IPeak> peakset = new IPeakSet<IPeak>(peaks); parseIPeak(parent, peakset); return peakset; }
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); }
private void initAllowedHosts(Document pDoc) { NodeList nodes = pDoc.getElementsByTagName("remote"); if (nodes.getLength() == 0) { // No restrictions found allowedHostsSet = null; return; } allowedHostsSet = new HashSet<String>(); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); NodeList childs = node.getChildNodes(); for (int j = 0; j < childs.getLength(); j++) { Node hostNode = childs.item(j); if (hostNode.getNodeType() != Node.ELEMENT_NODE) { continue; } assertNodeName(hostNode, "host"); String host = hostNode.getTextContent().trim().toLowerCase(); if (SUBNET_PATTERN.matcher(host).matches()) { if (allowedSubnetsSet == null) { allowedSubnetsSet = new HashSet<String>(); } allowedSubnetsSet.add(host); } else { allowedHostsSet.add(host); } } } }
private void buildHierarchyDOM() { TransformerFactory factory = TransformerFactory.newInstance(); StreamSource src = new StreamSource( this.getServletContext() .getResourceAsStream("/WEB-INF/classes/gpt/search/browse/ownerHierarchy.xml")); log.info("initializing src from stream " + src); try { Transformer t = factory.newTransformer(); dom = new DOMResult(); t.transform(src, dom); // now go thru tree, setting up the query attribute for each node Node tree = dom.getNode(); NodeList children = tree.getChildNodes(); log.info("dom tree contains " + children.getLength() + " nodes"); for (int i = 0; i < children.getLength(); i++) { Node child = children.item(i); if (child.getNodeType() == Node.ELEMENT_NODE) { Element e = (Element) child; String query = computeQuery(e); e.setAttribute("query", query); } } } catch (Exception e) { log.severe("Could not init ownerHierarchy because exception thrown:"); StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); log.severe(sw.toString()); } }
public List parsePage(String pageCode) { List sections = new ArrayList(); List folders = new ArrayList(); List files = new ArrayList(); int start = pageCode.indexOf("<div id=\"list-view\" class=\"view\""); int end = pageCode.indexOf("<div id=\"gallery-view\" class=\"view\""); String usefulSection = ""; if (start != -1 && end != -1) { usefulSection = pageCode.substring(start, end); } else { debug("Could not parse page"); } try { DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder(); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(usefulSection)); Document doc = db.parse(is); NodeList divs = doc.getElementsByTagName("div"); for (int i = 0; i < divs.getLength(); i++) { Element div = (Element) divs.item(i); boolean isFolder = false; if (div.getAttribute("class").equals("filename")) { NodeList imgs = div.getElementsByTagName("img"); for (int j = 0; j < imgs.getLength(); j++) { Element img = (Element) imgs.item(j); if (img.getAttribute("class").indexOf("folder") > 0) { isFolder = true; } else { isFolder = false; // it's a file } } NodeList anchors = div.getElementsByTagName("a"); Element anchor = (Element) anchors.item(0); String attr = anchor.getAttribute("href"); String fileName = anchor.getAttribute("title"); String fileURL; if (isFolder && !attr.equals("#")) { folders.add(attr); folders.add(fileName); } else if (!isFolder && !attr.equals("#")) { // Dropbox uses ajax to get the file for download, so the url isn't enough. We must be // sneaky here. fileURL = "https://dl.dropbox.com" + attr.substring(23) + "?dl=1"; files.add(fileURL); files.add(fileName); } } } } catch (Exception e) { debug(e.toString()); } sections.add(files); sections.add(folders); return sections; }
/** * parse plants.xml to get all plants information * * @param root * @return */ public static ArrayList<Plants> getPlant(Node root) { ArrayList<Plants> p = new ArrayList<Plants>(); String code = null; String common = null; String botanical = null; String light = null; String zone = null; String price = null; String available = null; root.getChildNodes(); for (int i = 0; i < root.getChildNodes().getLength(); i++) { Node state = root.getChildNodes().item(i); if (state.getNodeType() == Node.ELEMENT_NODE) { code = state.getAttributes().getNamedItem("code").getNodeValue(); NodeList plantNodes = state.getChildNodes(); for (int j = 0; j < plantNodes.getLength(); j++) { Node plant = plantNodes.item(j); if (plant.getNodeType() == Node.ELEMENT_NODE) { // get the pointer point to the node list of plant NodeList plantChildren = plant.getChildNodes(); int m = 0; for (int k = 0; k < plantChildren.getLength(); k++) { if (plantChildren.item(k).getNodeType() == Node.ELEMENT_NODE) { m++; NodeList textNodes = plantChildren.item(k).getChildNodes(); for (int n = 0; n < textNodes.getLength(); n++) { if (textNodes.item(n).getNodeType() == Node.TEXT_NODE) { switch (m) { case 1: common = textNodes.item(n).getNodeValue(); break; case 2: botanical = textNodes.item(n).getNodeValue(); break; case 3: zone = textNodes.item(n).getNodeValue(); break; case 4: light = textNodes.item(n).getNodeValue(); break; case 5: price = textNodes.item(n).getNodeValue().substring(1); break; case 6: available = textNodes.item(n).getNodeValue(); break; } } } } } p.add(new Plants(code, common, botanical, zone, light, price, available)); } } } } return p; }
public ResultValue(Node node) { NodeList list = node.getChildNodes(); for (int i = 0; i < list.getLength(); i++) { Node n = list.item(i); if (n.getNodeName().equals("class")) { matlabClass = n.getTextContent(); } if (n.getNodeName().equals("size")) { size = string2intList(n.getTextContent()); numdims = size.size(); numel = 1; for (int d : size) { numel *= d; } } if (n.getNodeName().equals("matrix")) { resultType = RESULT_TYPE.MATRIX; matrixResult = string2doubleList(n.getTextContent()); } if (n.getNodeName().equals("imagMatrix")) { isReal = false; resultType = RESULT_TYPE.MATRIX; imagMatrixResult = string2doubleList(n.getTextContent()); } if (n.getNodeName().equals("char")) { resultType = RESULT_TYPE.CHAR; charResult = n.getTextContent(); } if (n.getNodeName().equals("logical")) { resultType = RESULT_TYPE.LOGICAL; logicalResult = string2booleanList(n.getTextContent()); } if (n.getNodeName().equals("handle")) { resultType = RESULT_TYPE.HANDLE; } if (n.getNodeName().equals("struct")) { resultType = RESULT_TYPE.STRUCT; // create struct list for first occurence of struct if (structResult == null) { structResult = new ArrayList<HashMap<String, ResultValue>>(); } // build struct HashMap<String, ResultValue> struct = new HashMap<String, ResultValue>(); NodeList children = n.getChildNodes(); for (int j = 0; j < children.getLength(); j++) { Node child = children.item(j); if (child.getNodeType() == Node.ELEMENT_NODE) { struct.put(child.getNodeName(), new ResultValue(child)); } } structResult.add(struct); } if (n.getNodeName().equals("cell")) { resultType = RESULT_TYPE.CELL; } } }
void lookup(String text) { NodeList nl = DOMInfoExtractor.locateNodes(document, ".//text()[contains(.,'" + text + "')]"); System.out.println("find " + nl.getLength() + " items"); FoundItem[] fis = new FoundItem[nl.getLength()]; for (int i = 0; i < nl.getLength(); i++) { fis[i] = getFoundItem(nl.item(i), text); } foundList.setListData(fis); }
/** * Carries out preprocessing that makes JEuclid handle the document better. * * @param doc Document */ static void preprocessForJEuclid(Document doc) { // underbrace and overbrace NodeList list = doc.getElementsByTagName("mo"); for (int i = 0; i < list.getLength(); i++) { Element mo = (Element) list.item(i); String parentName = ((Element) mo.getParentNode()).getTagName(); if (parentName == null) { continue; } if (parentName.equals("munder") && isTextChild(mo, "\ufe38")) { mo.setAttribute("stretchy", "true"); mo.removeChild(mo.getFirstChild()); mo.appendChild(doc.createTextNode("\u23df")); } else if (parentName.equals("mover") && isTextChild(mo, "\ufe37")) { mo.setAttribute("stretchy", "true"); mo.removeChild(mo.getFirstChild()); mo.appendChild(doc.createTextNode("\u23de")); } } // menclose for long division doesn't allow enough top padding. Oh, and // <mpadded> isn't implemented. And there isn't enough padding to left of // the bar either. Solve by adding an <mover> with just an <mspace> over# // the longdiv, contained within an mrow that adds a <mspace> before it. list = doc.getElementsByTagName("menclose"); for (int i = 0; i < list.getLength(); i++) { Element menclose = (Element) list.item(i); // Only for longdiv if (!"longdiv".equals(menclose.getAttribute("notation"))) { continue; } Element mrow = doc.createElementNS(WebMathsService.NS, "mrow"); Element mover = doc.createElementNS(WebMathsService.NS, "mover"); Element mspace = doc.createElementNS(WebMathsService.NS, "mspace"); Element mspaceW = doc.createElementNS(WebMathsService.NS, "mspace"); boolean previousElement = false; for (Node previous = menclose.getPreviousSibling(); previous != null; previous = previous.getPreviousSibling()) { if (previous.getNodeType() == Node.ELEMENT_NODE) { previousElement = true; break; } } if (previousElement) { mspaceW.setAttribute("width", "4px"); } menclose.getParentNode().insertBefore(mrow, menclose); menclose.getParentNode().removeChild(menclose); mrow.appendChild(mspaceW); mrow.appendChild(mover); mover.appendChild(menclose); mover.appendChild(mspace); } }
private void loadFromXml(String fileName) throws ParserConfigurationException, SAXException, IOException, ParseException { System.out.println("NeuralNetwork : loading network topology from file " + fileName); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder parser = factory.newDocumentBuilder(); Document doc = parser.parse(fileName); Node nodeNeuralNetwork = doc.getDocumentElement(); if (!nodeNeuralNetwork.getNodeName().equals("neuralNetwork")) throw new ParseException( "[Error] NN-Load: Parse error in XML file, neural network couldn't be loaded.", 0); // nodeNeuralNetwork ok // indexNeuralNetworkContent -> indexStructureContent -> indexLayerContent -> indexNeuronContent // -> indexNeuralInputContent NodeList nodeNeuralNetworkContent = nodeNeuralNetwork.getChildNodes(); for (int innc = 0; innc < nodeNeuralNetworkContent.getLength(); innc++) { Node nodeStructure = nodeNeuralNetworkContent.item(innc); if (nodeStructure.getNodeName().equals("structure")) { // for structure element NodeList nodeStructureContent = nodeStructure.getChildNodes(); for (int isc = 0; isc < nodeStructureContent.getLength(); isc++) { Node nodeLayer = nodeStructureContent.item(isc); if (nodeLayer.getNodeName().equals("layer")) { // for layer element NeuralLayer neuralLayer = new NeuralLayer(this); this.listLayers.add(neuralLayer); NodeList nodeLayerContent = nodeLayer.getChildNodes(); for (int ilc = 0; ilc < nodeLayerContent.getLength(); ilc++) { Node nodeNeuron = nodeLayerContent.item(ilc); if (nodeNeuron.getNodeName().equals("neuron")) { // for neuron in layer Neuron neuron = new Neuron( Double.parseDouble(((Element) nodeNeuron).getAttribute("threshold")), neuralLayer); neuralLayer.listNeurons.add(neuron); NodeList nodeNeuronContent = nodeNeuron.getChildNodes(); for (int inc = 0; inc < nodeNeuronContent.getLength(); inc++) { Node nodeNeuralInput = nodeNeuronContent.item(inc); // if (nodeNeuralInput==null) System.out.print("-"); else System.out.print("*"); if (nodeNeuralInput.getNodeName().equals("input")) { // System.out.println("neuron at // STR:"+innc+" LAY:"+isc+" NEU:"+ilc+" INP:"+inc); NeuralInput neuralInput = new NeuralInput( Double.parseDouble(((Element) nodeNeuralInput).getAttribute("weight")), neuron); neuron.listInputs.add(neuralInput); } } } } } } } } }
public void getClassName() { try { DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); Document doc = docBuilder.parse(new File("src/resources/classdata.xml")); doc.getDocumentElement().normalize(); NodeList listOfClasses = doc.getElementsByTagName("class"); classes = new String[listOfClasses.getLength()]; amountClasses = listOfClasses.getLength(); String classID; String className; int classIDint; for (int s = 0; s < listOfClasses.getLength(); s++) { Node firstPersonNode = listOfClasses.item(s); if (firstPersonNode.getNodeType() == Node.ELEMENT_NODE) { Element firstClassElement = (Element) firstPersonNode; NodeList idList = firstClassElement.getElementsByTagName("id"); Element idElement = (Element) idList.item(0); NodeList textLNList = idElement.getChildNodes(); classID = ((Node) textLNList.item(0)).getNodeValue().trim(); NodeList NameList = firstClassElement.getElementsByTagName("name"); Element NameElement = (Element) NameList.item(0); NodeList textFNList = NameElement.getChildNodes(); className = ((Node) textFNList.item(0)).getNodeValue().trim(); classIDint = Integer.parseInt(classID); classes[classIDint] = className; } // end of if clause } // end of for loop with s var } catch (SAXParseException err) { System.out.println( "** Parsing error" + ", line " + err.getLineNumber() + ", uri " + err.getSystemId()); System.out.println(" " + err.getMessage()); } catch (SAXException e) { Exception x = e.getException(); ((x == null) ? e : x).printStackTrace(); } catch (Throwable t) { t.printStackTrace(); } // System.exit (0); }
public Node item(int index) { int relativeIndex = index; for (int i = 0; i < nodeLists.size(); i++) { NodeList nl = (NodeList) nodeLists.get(i); if (relativeIndex < nl.getLength()) { return nl.item(relativeIndex); } relativeIndex -= nl.getLength(); } return null; }
void lookupByXPath(String xpath) { NodeList nl = DOMInfoExtractor.locateNodes(document, xpath); System.out.println("lookupByXPath: " + xpath); if (nl == null) { JOptionPane.showMessageDialog(this, "error xpath: " + xpath); } System.out.println("find " + nl.getLength() + " items"); FoundItem[] fis = new FoundItem[nl.getLength()]; for (int i = 0; i < nl.getLength(); i++) { fis[i] = getFoundItem(nl.item(i), null); } foundList.setListData(fis); }
public apiParser(String sdkfile) { System.out.println(sdkfile); File file = new File(sdkfile); try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(file); NodeList apiList = doc.getElementsByTagName("n1:api"); NodeList inputList = doc.getElementsByTagName("n1:input"); NodeList typeList = doc.getElementsByTagName("n1:type"); for (int i = 0; i < apiList.getLength(); i++) { Node api_node = apiList.item(i); String api_id = api_node.getAttributes().getNamedItem("id").getNodeValue(); String api_name = api_node.getAttributes().getNamedItem("name").getNodeValue(); String input_type_id = inputList.item(i).getAttributes().getNamedItem("type_ref").getNodeValue(); // System.out.println(api_id + " : " + api_name + " : " + input_type_id); ArrayList<String> api_params = new ArrayList<String>(); for (int j = 0; j < typeList.getLength(); j++) { if (input_type_id.equalsIgnoreCase( typeList.item(j).getAttributes().getNamedItem("id").getNodeValue())) { Element e1 = (Element) typeList.item(j); NodeList param_l = e1.getElementsByTagName("n1:param"); for (int k = 0; k < param_l.getLength(); k++) { String param_name = param_l.item(k).getAttributes().getNamedItem("name").getNodeValue(); // String param_desc = // param_l.item(k).getAttributes().getNamedItem("desc").getNodeValue(); api_params.add(param_name); // System.out.println(param_name +":"+param_desc); } break; } } apiRoom s_room = new apiRoom(api_id, api_name, api_params); apiRooms.add(s_room); } } catch (Exception e) { e.printStackTrace(); } }
/** * Examine the areaspec and determine the number and position of callouts. * * <p>The <code><a href="http://docbook.org/tdg/html/areaspec.html">areaspecNodeSet</a></code> is * examined and a sorted list of the callouts is constructed. * * <p>This data structure is used to augment the result tree fragment with callout bullets. * * @param areaspecNodeSet The source document <areaspec> element. */ public void setupCallouts(NodeList areaspecNodeList) { callout = new Callout[10]; calloutCount = 0; calloutPos = 0; lineNumber = 1; colNumber = 1; // First we walk through the areaspec to calculate the position // of the callouts // <areaspec> // <areaset id="ex.plco.const" coords=""> // <area id="ex.plco.c1" coords="4"/> // <area id="ex.plco.c2" coords="8"/> // </areaset> // <area id="ex.plco.ret" coords="12"/> // <area id="ex.plco.dest" coords="12"/> // </areaspec> int pos = 0; int coNum = 0; boolean inAreaSet = false; Node areaspec = areaspecNodeList.item(0); NodeList children = areaspec.getChildNodes(); for (int count = 0; count < children.getLength(); count++) { Node node = children.item(count); if (node.getNodeType() == Node.ELEMENT_NODE) { if (node.getNodeName().equalsIgnoreCase("areaset")) { coNum++; NodeList areas = node.getChildNodes(); for (int acount = 0; acount < areas.getLength(); acount++) { Node area = areas.item(acount); if (area.getNodeType() == Node.ELEMENT_NODE) { if (area.getNodeName().equalsIgnoreCase("area")) { addCallout(coNum, area, defaultColumn); } else { System.out.println("Unexpected element in areaset: " + area.getNodeName()); } } } } else if (node.getNodeName().equalsIgnoreCase("area")) { coNum++; addCallout(coNum, node, defaultColumn); } else { System.out.println("Unexpected element in areaspec: " + node.getNodeName()); } } } // Now sort them java.util.Arrays.sort(callout, 0, calloutCount); }
/** @see com.levelonelabs.aim.XMLizable#readState(Element) */ public void readState(Element fullStateElement) { // parse group String group = fullStateElement.getAttribute("group"); if (group == null || group.trim().equals("")) { group = AIMSender.DEFAULT_GROUP; } setGroup(group); // parse banned String ban = fullStateElement.getAttribute("isBanned"); if (ban.equalsIgnoreCase("true")) { setBanned(true); } else { setBanned(false); } // parse roles roles = new HashMap(); NodeList list = fullStateElement.getElementsByTagName("role"); for (int i = 0; i < list.getLength(); i++) { Element roleElem = (Element) list.item(i); String role = roleElem.getAttribute("name"); addRole(role); } // parse messages messages = new ArrayList(); list = fullStateElement.getElementsByTagName("message"); for (int i = 0; i < list.getLength(); i++) { Element messElem = (Element) list.item(i); NodeList cdatas = messElem.getChildNodes(); for (int j = 0; j < cdatas.getLength(); j++) { Node node = cdatas.item(j); if (node.getNodeType() == Node.CDATA_SECTION_NODE) { String message = node.getNodeValue(); addMessage(message); break; } } } // parse prefs preferences = new HashMap(); list = fullStateElement.getElementsByTagName("preference"); for (int i = 0; i < list.getLength(); i++) { Element prefElem = (Element) list.item(i); String pref = prefElem.getAttribute("name"); String val = prefElem.getAttribute("value"); this.setPreference(pref, val); } }
public static ArrayList<String> getFilterNames() { ArrayList<String> filters = new ArrayList<String>(); try { DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); Document doc = docBuilder.parse(new File("filters.xml")); // normalize text representation doc.getDocumentElement().normalize(); NodeList listOfPersons = doc.getElementsByTagName("filter"); int totalPersons = listOfPersons.getLength(); System.out.println("Total of filters : " + totalPersons); for (int s = 0; s < listOfPersons.getLength(); s++) { Node firstPersonNode = listOfPersons.item(s); if (firstPersonNode.getNodeType() == Node.ELEMENT_NODE) { Element firstPersonElement = (Element) firstPersonNode; // ------- NodeList firstNameList = firstPersonElement.getElementsByTagName("name"); Element firstNameElement = (Element) firstNameList.item(0); NodeList textFNList = firstNameElement.getChildNodes(); System.out.println("Filter Name : " + ((Node) textFNList.item(0)).getNodeValue().trim()); filters.add(((Node) textFNList.item(0)).getNodeValue().trim()); } // end of if clause } // end of for loop with s var } catch (SAXParseException err) { System.out.println( "** Parsing error" + ", line " + err.getLineNumber() + ", uri " + err.getSystemId()); System.out.println(" " + err.getMessage()); } catch (SAXException e) { Exception x = e.getException(); ((x == null) ? e : x).printStackTrace(); } catch (Throwable t) { t.printStackTrace(); } // System.exit (0); return filters; } // end of main
public static ArrayList<String> getTextValue(Element ele, String tagName) { ArrayList<String> returnVal = new ArrayList<String>(); // NodeList nll = ele.getElementsByTagName("*"); NodeList nl = ele.getElementsByTagName(tagName); if (nl != null && nl.getLength() > 0) { for (int i = 0; i < nl.getLength(); i++) { Element el = (Element) nl.item(i); returnVal.add(el.getFirstChild().getNodeValue()); } } return returnVal; }
/** * parse states.xml to get all states information * * @param root * @param plantList * @return */ public static ArrayList<State> getState(Node root, ArrayList<Plants> plantList) { ArrayList<State> s = new ArrayList<State>(); String code = null; String name = null; String nickname = null; String zone = null; State st = null; NodeList states = root.getChildNodes(); for (int i = 0; i < root.getChildNodes().getLength(); i++) { if (states.item(i).getNodeType() == Node.ELEMENT_NODE) { code = states.item(i).getAttributes().getNamedItem("code").getNodeValue(); Node state = states.item(i); NodeList stateChildren = state.getChildNodes(); int m = 0; for (int j = 0; j < stateChildren.getLength(); j++) { if (stateChildren.item(j).getNodeType() == Node.ELEMENT_NODE) { m++; NodeList text = stateChildren.item(j).getChildNodes(); for (int k = 0; k < text.getLength(); k++) { if (text.item(k).getNodeType() == Node.TEXT_NODE) { switch (m) { case 1: name = text.item(k).getNodeValue(); break; case 2: nickname = text.item(k).getNodeValue(); break; case 3: zone = text.item(k).getNodeValue(); } } } } } st = new State(code, name, nickname, zone, new ArrayList<Plants>()); s.add(st); } } for (int m = 0; m < s.size(); m++) { for (int n = 0; n < plantList.size(); n++) { if (plantList.get(n).getCode().equals(s.get(m).getCode())) { s.get(m).setPlants(plantList.get(n)); } } } return s; }
public XMLHelper[] getSubNodeList(String subnode) { int pos = subnode.lastIndexOf(DELIM); if (pos >= 0) { XMLHelper helper = getSubNode(subnode.substring(0, pos)); return helper.getSubNodeList(subnode.substring(pos + 1)); } else { NodeList list = getImediateElementsByTagName(subnode); XMLHelper[] results = new XMLHelper[list.getLength()]; int length = list.getLength(); for (int i = 0; i < length; i++) { results[i] = new XMLHelper((Element) list.item(i)); } return results; } }
/** * Converts an XML element into an <code>EppCommandRenewXriName</code> object. The caller of this * method must make sure that the root node is of an EPP Command Renew entity for EPP XRI I-Name * object * * @param root root node for an <code>EppCommandRenewXriName</code> object in XML format * @return an <code>EppCommandRenewXriName</code> object, or null if the node is invalid */ public static EppEntity fromXML(Node root) { EppCommandRenewXriName cmd = null; String iname = null; Calendar curExpDate = null; EppPeriod period = null; NodeList list = root.getChildNodes(); for (int i = 0; i < list.getLength(); i++) { Node node = list.item(i); String name = node.getLocalName(); if (name == null) { continue; } if (name.equals("iname")) { iname = EppUtil.getText(node); } else if (name.equals("curExpDate")) { curExpDate = EppUtil.getDate(node, true); } else if (name.equals("period")) { period = (EppPeriod) EppPeriod.fromXML(node); } } if (iname != null) { cmd = new EppCommandRenewXriName(iname, curExpDate, period, null); } return cmd; }
public IXArchElement cloneElement(int depth) { synchronized (DOMUtils.getDOMLock(elt)) { Document doc = elt.getOwnerDocument(); if (depth == 0) { Element cloneElt = (Element) elt.cloneNode(false); cloneElt = (Element) doc.importNode(cloneElt, true); AbstractChangeSetImpl cloneImpl = new AbstractChangeSetImpl(cloneElt); cloneImpl.setXArch(getXArch()); return cloneImpl; } else if (depth == 1) { Element cloneElt = (Element) elt.cloneNode(false); cloneElt = (Element) doc.importNode(cloneElt, true); AbstractChangeSetImpl cloneImpl = new AbstractChangeSetImpl(cloneElt); cloneImpl.setXArch(getXArch()); NodeList nl = elt.getChildNodes(); int size = nl.getLength(); for (int i = 0; i < size; i++) { Node n = nl.item(i); Node cloneNode = (Node) n.cloneNode(false); cloneNode = doc.importNode(cloneNode, true); cloneElt.appendChild(cloneNode); } return cloneImpl; } else /* depth = infinity */ { Element cloneElt = (Element) elt.cloneNode(true); cloneElt = (Element) doc.importNode(cloneElt, true); AbstractChangeSetImpl cloneImpl = new AbstractChangeSetImpl(cloneElt); cloneImpl.setXArch(getXArch()); return cloneImpl; } } }
/** childNodes, hasChildNodes. */ public void testChildNodeList() { Document doc = Document.get(); BodyElement body = doc.getBody(); // <div>foo<button/>bar</div> DivElement div = doc.createDivElement(); Text txt0 = doc.createTextNode("foo"); ButtonElement btn0 = doc.createButtonElement(); Text txt1 = doc.createTextNode("bar"); body.appendChild(div); div.appendChild(txt0); div.appendChild(btn0); div.appendChild(txt1); NodeList<Node> children = div.getChildNodes(); assertEquals(3, children.getLength()); assertEquals(txt0, children.getItem(0)); assertEquals(btn0, children.getItem(1)); assertEquals(txt1, children.getItem(2)); assertEquals(3, div.getChildCount()); assertEquals(txt0, div.getChild(0)); assertEquals(btn0, div.getChild(1)); assertEquals(txt1, div.getChild(2)); assertFalse(txt0.hasChildNodes()); assertTrue(div.hasChildNodes()); }
/** * Runs the test case. * * @throws Throwable Any uncaught exception causes test to fail */ public void runTest() throws Throwable { Document doc; NodeList elementList; Node employeeNode; Node childNode; NodeList childNodes; int nodeType; String childName; java.util.List actual = new java.util.ArrayList(); java.util.List expected = new java.util.ArrayList(); expected.add("em"); expected.add("strong"); expected.add("code"); expected.add("sup"); expected.add("var"); expected.add("acronym"); doc = (Document) load("hc_staff", false); elementList = doc.getElementsByTagName("p"); employeeNode = elementList.item(1); childNodes = employeeNode.getChildNodes(); for (int indexN1006C = 0; indexN1006C < childNodes.getLength(); indexN1006C++) { childNode = (Node) childNodes.item(indexN1006C); nodeType = (int) childNode.getNodeType(); childName = childNode.getNodeName(); if (equals(1, nodeType)) { actual.add(childName); } else { assertEquals("textNodeType", 3, nodeType); } } assertEqualsAutoCase("element", "elementNames", expected, actual); }
/** * Pretty prints a node. * * @param doc The document the node comes from. * @param node The node that should be pretty printed. */ public static void prettyPrint(Document doc, Node node) { // Get the text before the node and extract the indenting Node parent = node.getParentNode(); String indenting = ""; NodeList siblingList = parent.getChildNodes(); for (int i = 1; i < siblingList.getLength(); i++) { Node sibling = siblingList.item(i); if (sibling == node) { Node nodeBefore = siblingList.item(i - 1); // Check whether this is a text node if (nodeBefore.getNodeName().equals("#text")) { // There is text before the node -> Extract the indenting String text = nodeBefore.getNodeValue(); int newlinePos = text.lastIndexOf('\n'); if (newlinePos != -1) { indenting = text.substring(newlinePos); if (indenting.trim().length() != 0) { // The indenting is no whitespace -> Forget it indenting = ""; } } } break; } } // Now pretty print the node prettyPrint(doc, node, indenting); }
private void gatherNamespaces(Element element, List<URI> namespaceSources) throws SAXException { NamedNodeMap attributes = element.getAttributes(); int attributeCount = attributes.getLength(); for (int i = 0; i < attributeCount; i++) { Attr attribute = (Attr) attributes.item(i); String namespace = attribute.getNamespaceURI(); if (XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(namespace)) { try { namespaceSources.add(new URI(attribute.getValue())); } catch (URISyntaxException e) { throw new SAXException( "Cannot validate this document with this class. Namespaces must be valid URIs. Found Namespace: '" + attribute.getValue() + "'.", e); } } } NodeList childNodes = element.getChildNodes(); int childCount = childNodes.getLength(); for (int i = 0; i < childCount; i++) { Node child = childNodes.item(i); if (child.getNodeType() == Node.ELEMENT_NODE) { gatherNamespaces((Element) child, namespaceSources); } } }
/** * Pretty prints a node. * * @param doc The document the node comes from. * @param node The node that should be pretty printed. * @param prefix The prefix the node should get. */ private static void prettyPrint(Document doc, Node node, String prefix) { String childPrefix = prefix + " "; // Add the indenting to the children NodeList childList = node.getChildNodes(); boolean hasChildren = false; for (int i = childList.getLength() - 1; i >= 0; i--) { Node child = childList.item(i); boolean isNormalNode = (!child.getNodeName().startsWith("#")); if (isNormalNode) { // Add the indenting to this node Node textNode = doc.createTextNode(childPrefix); node.insertBefore(textNode, child); // pretty print the child's children prettyPrint(doc, child, childPrefix); hasChildren = true; } } // Add the indenting to the end tag if (hasChildren) { Node textNode = doc.createTextNode(prefix); node.appendChild(textNode); } }