private final void roundTrip(boolean expand, boolean validating, String encoding, String expect) { String docloc = this.getClass().getPackage().getName().replaceAll("\\.", "/") + "/TestIssue008.xml"; URL docurl = ClassLoader.getSystemResource(docloc); if (docurl == null) { throw new IllegalStateException("Unable to get resource " + docloc); } SAXBuilder builder = new SAXBuilder(validating); // builder.setValidation(validating); builder.setExpandEntities(expand); Document doc = null; try { doc = builder.build(docurl); } catch (JDOMException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } if (doc == null) { fail("Unable to parse document, see output."); } Format fmt = Format.getCompactFormat(); if (encoding != null) { fmt.setEncoding(encoding); } XMLOutputter xout = new XMLOutputter(fmt); String actual = xout.outputString(doc.getRootElement()); assertEquals(expect, actual); }
private org.jdom2.Element getDataforCase(String specName, String caseID, String data) { String caseData = ""; try { caseData = _ibClient.getCaseData(caseID, _handle); } catch (IOException e) { e.printStackTrace(); } org.jdom2.Element result = new org.jdom2.Element(specName); SAXBuilder builder = new SAXBuilder(); org.jdom2.Element root = null; List<org.jdom2.Element> ls = null; try { org.jdom2.Document document = builder.build(new StringReader(data)); root = document.getRootElement(); ls = document.getRootElement().getChildren(); } catch (Exception e) { System.out.println(e); } for (org.jdom2.Element l : ls) { String paramName = l.getName(); org.jdom2.Element advElem = root.getChild(paramName); try { if (advElem != null) { org.jdom2.Element copy = (org.jdom2.Element) advElem.clone(); result.addContent(copy); } else { result.addContent(new org.jdom2.Element(paramName)); } } catch (IllegalAddException iae) { } } return result; }
/** * Add a button to main.xml. * * @param text The displayed text * @param buttonId The button id */ private void addButtonToMainXML(final String text, final String buttonId) { String xmlFileName = this.adapter.getRessourceLayoutPath() + "main.xml"; Document doc = XMLUtils.openXML(xmlFileName); Namespace androidNs = doc.getRootElement().getNamespace("android"); Element linearL = doc.getRootElement().getChild("LinearLayout"); boolean alreadyExists = false; for (Element element : linearL.getChildren("Button")) { if (element.getAttributeValue("id", androidNs).equals("@+id/" + buttonId)) { alreadyExists = true; } } if (!alreadyExists) { Element newButton = new Element("Button"); newButton.setAttribute("id", "@+id/" + buttonId, androidNs); newButton.setAttribute("layout_width", "match_parent", androidNs); newButton.setAttribute("layout_height", "wrap_content", androidNs); newButton.setAttribute("text", text, androidNs); linearL.addContent(newButton); } XMLUtils.writeXMLToFile(doc, xmlFileName); }
void metaVersusData(File p_file) throws Exception { SAXBuilder leftBuilder = new SAXBuilder(); Document doc = leftBuilder.build(p_file); metaVersusData(doc.getRootElement()); }
private String chooserQuery() { Random r = new Random(); File experimentFile = new File(queryFile); SAXBuilder sb = new SAXBuilder(); Document d = null; try { d = sb.build(experimentFile); } catch (JDOMException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } List<String> queries = new ArrayList<String>(); Element jpameterTag = d.getRootElement(); Element queriesTag = jpameterTag.getChild("queries"); List<Element> query = queriesTag.getChildren(); for (Element e : query) { Element type = e.getChild("type"); if (Integer.parseInt(type.getValue()) == typeQuery + 1) { Element sql = e.getChild("sql"); queries.add(sql.getValue()); } } if (queries.size() > 0) return queries.get(r.nextInt(queries.size())); else return null; }
/* * 初始化signlist */ private static void initSignList() { SAXBuilder builder = new SAXBuilder(); Document read_doc = null; try { read_doc = builder.build("./bin/com/fc/config/operator.xml"); } catch (JDOMException | IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } SignInfo si = null; Element stu = read_doc.getRootElement(); // 读取根节点 List<Element> list = stu.getChildren("binaryOperator"); // 获取根元素的所有子节点 List<Element> unarylist = stu.getChildren("unaryOperator"); for (int i = 0; i < list.size(); i++) { // 遍历子节点,并取出其属性、子节点的文本。 Element e = list.get(i); String classURL = e.getChildText("class"); String name = e.getAttribute("name").getValue(); String pri = e.getAttribute("priority").getValue(); si = new SignInfo(name, classURL, Integer.parseInt(pri)); signlist.put(name, si); } for (int i = 0; i < unarylist.size(); i++) { // 遍历子节点,并取出其属性、子节点的文本。 Element e = unarylist.get(i); String classURL = e.getChildText("class"); String name = e.getAttribute("name").getValue(); String pri = e.getAttribute("priority").getValue(); si = new SignInfo(name, classURL, Integer.parseInt(pri)); signlist.put(name, si); } }
public String formatAsXHTML(String xhtml) throws IOException, JDOMException { DocType doctype = new DocType( "html", "-//W3C//DTD XHTML 1.1//EN", "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"); Namespace namespace = Namespace.getNamespace("http://www.w3.org/1999/xhtml"); org.jdom2.Document document = XHTMLUtils.parseXHTMLDocument(xhtml); org.jdom2.Element root = document.getRootElement(); root.setNamespace(namespace); root.addNamespaceDeclaration(namespace); IteratorIterable<org.jdom2.Element> elements = root.getDescendants(Filters.element()); for (org.jdom2.Element element : elements) { if (element.getNamespace() == null) { element.setNamespace(Constants.NAMESPACE_XHTML); } } document.setDocType(doctype); XMLOutputter outputter = new XMLOutputter(); Format xmlFormat = Format.getPrettyFormat(); outputter.setFormat(xmlFormat); outputter.setXMLOutputProcessor(new XHTMLOutputProcessor()); String result = outputter.outputString(document); return result; }
private void addNoiseAbstractedMetadata(final MetadataElement origProdRoot) throws IOException { MetadataElement noiseElement = origProdRoot.getElement("noise"); if (noiseElement == null) { noiseElement = new MetadataElement("noise"); origProdRoot.addElement(noiseElement); } final String calibFolder = getRootFolder() + "annotation" + '/' + "calibration"; final String[] filenames = listFiles(calibFolder); if (filenames != null) { for (String metadataFile : filenames) { if (metadataFile.startsWith("noise")) { final Document xmlDoc = XMLSupport.LoadXML(getInputStream(calibFolder + '/' + metadataFile)); final Element rootElement = xmlDoc.getRootElement(); final String name = metadataFile.replace("noise-", ""); final MetadataElement nameElem = new MetadataElement(name); noiseElement.addElement(nameElem); AbstractMetadataIO.AddXMLMetadata(rootElement, nameElem); } } } }
public static List<String> getEventsNameByXml() { SAXBuilder sxb = new SAXBuilder(); Document document; List<String> listEvenementsString = null; // Object obj=null; try { document = sxb.build(new File(xmlDefaultPath)); // listevents=getEventsNameByDoc(document); Element racine = document.getRootElement(); // System.out.println("racine="+racine.getText()+"finracine"); List<Element> listEvenementsElement = racine.getChildren("evenement"); listEvenementsString = new ArrayList<String>(); for (Element evenementElement : listEvenementsElement) { listEvenementsString.add(evenementElement.getAttributeValue("nomEvent")); } // System.out.println("listofEventsJdomtaille ="+listEvenementsString.size()); // il faut valider le fichier xml avec la dtd // JDomOperations.validateJDOM(document); // afficheXml(document); } catch (Exception e) { // afficher un popup qui dit que le format du fichier xml entré n'est pas valide System.out.println("format xml non respecté"); System.out.println(e.getMessage()); } return listEvenementsString; }
@Test public void exportPreferences_setsVersionToLatest() throws Exception { Document document = exportPreferences(false, Collections.<String>emptySet()); assertEquals( Integer.toString(Settings.VERSION), document.getRootElement().getAttributeValue("version")); }
public Element getFileRoot(String filename) { // find file & load file Element root = null; boolean verify = false; try { SAXBuilder builder = new SAXBuilder("org.apache.xerces.parsers.SAXParser", verify); builder.setFeature("http://apache.org/xml/features/xinclude", true); builder.setFeature("http://apache.org/xml/features/xinclude/fixup-base-uris", false); builder.setFeature("http://apache.org/xml/features/allow-java-encodings", true); builder.setFeature("http://apache.org/xml/features/validation/schema", verify); builder.setFeature("http://apache.org/xml/features/validation/schema-full-checking", verify); builder.setFeature("http://xml.org/sax/features/namespaces", true); Document doc = builder.build(new BufferedInputStream(new FileInputStream(new File(filename)))); root = doc.getRootElement(); } catch (Exception e) { System.out.println("While reading file: " + e); } return root; }
public static void removeEventinXml(String eventNameString) { SAXBuilder sxbuilder = new SAXBuilder(); try { Document document = sxbuilder.build(new File(xmlDefaultPath)); Element racine = document.getRootElement(); // List listEvents = racine.getChildren("evenement"); // Iterator i = listEvents.iterator(); // while(i.hasNext()){ // Element elementEvent = (Element)i.next(); // if(elementEvent.getAttribute("nomEvent").getValue().equalsIgnoreCase(eventNameString)){ // racine.removeChild("evenement"); // } // } // // if(racine.getChild("evenement").getAttribute("nomEvent").getValue().equalsIgnoreCase(eventNameString)){ // // } // List<Element> children = racine.getChildren(); // for(Element child : children) { // // if(child.getAttribute("nomEvent").getValue().equalsIgnoreCase(eventNameString)){ // System.out.println("poins"); //// child.getParentElement().removeChild("evenement"); // System.out.println(child.getAttributeValue("nomEvent")); // } // } // enregistre(document, xmlDefaultPath); } catch (Exception e) { e.getMessage(); } }
private void setData() { try { Document doc = builder.build(prefFile); Element rootNode = doc.getRootElement(); Element RWDir = new Element("RWDir"); rootNode.getChild("firstLoad").setText("no"); RWDir.setText(RWDIRECTORY.getAbsolutePath()); rootNode.addContent(RWDir); XMLOutputter xmlOutput = new XMLOutputter(); FileWriter fw = new FileWriter(prefFile); xmlOutput.setFormat(Format.getPrettyFormat()); xmlOutput.output(doc, fw); fw.close(); } catch (IOException io) { io.printStackTrace(); } catch (JDOMException e) { e.printStackTrace(); } }
/** * Generate a default LoLStatus that can later be modified and be used to change the current * LolStatus ({@link LolChat#setStatus(LolStatus)}). */ public LolStatus() { outputter.setFormat(outputter.getFormat().setExpandEmptyElements(false)); doc = new Document(new Element("body")); for (final XMLProperty p : XMLProperty.values()) { doc.getRootElement().addContent(new Element(p.toString())); } }
public TableConfig readConfigXML( String fileLocation, FeatureType wantFeatureType, NetcdfDataset ds, Formatter errlog) throws IOException { org.jdom2.Document doc; try { SAXBuilder builder = new SAXBuilder(false); if (debugURL) System.out.println(" PointConfig URL = <" + fileLocation + ">"); doc = builder.build(fileLocation); } catch (JDOMException e) { throw new IOException(e.getMessage()); } if (debugXML) System.out.println(" SAXBuilder done"); if (showParsedXML) { XMLOutputter xmlOut = new XMLOutputter(); System.out.println( "*** PointConfig/showParsedXML = \n" + xmlOut.outputString(doc) + "\n*******"); } Element configElem = doc.getRootElement(); String featureType = configElem.getAttributeValue("featureType"); Element tableElem = configElem.getChild("table"); TableConfig tc = parseTableConfig(ds, tableElem, null); tc.featureType = FeatureType.valueOf(featureType); return tc; }
private String mapItemParamsToAdviceCaseParams( String adviceName, List<YParameter> inAspectParams, String data) { org.jdom2.Element result = new org.jdom2.Element(adviceName); SAXBuilder builder = new SAXBuilder(); org.jdom2.Element root = null; try { org.jdom2.Document document = builder.build(new StringReader(data)); root = document.getRootElement(); } catch (Exception e) { System.out.println(e); } for (YParameter param : inAspectParams) { String paramName = param.getName(); org.jdom2.Element advElem = root.getChild(paramName); try { if (advElem != null) { org.jdom2.Element copy = (org.jdom2.Element) advElem.clone(); result.addContent(copy); } else { result.addContent(new org.jdom2.Element(paramName)); } } catch (IllegalAddException iae) { System.out.println("+++++++++++++++++ error:" + iae.getMessage()); } } return JDOMUtil.elementToString(result); }
public static List getNcMLElements(String path, Document doc) { // XPath doesn't support default namespaces, so we add nc as a prefix for the tags within the // namespace!!! if (!path.startsWith(NS_PREFIX_ON_TAG) && !path.startsWith("/")) path = NS_PREFIX_ON_TAG + path; Pattern pattern = Pattern.compile("/\\w"); Matcher matcher = pattern.matcher(path); StringBuilder sb = new StringBuilder(); int currentChar = 0; while (matcher.find()) { sb.append(path.substring(currentChar, matcher.start() - currentChar + 1)); if (!sb.toString().endsWith("/")) sb.append("/"); sb.append(NS_PREFIX_ON_TAG); currentChar = matcher.start() + 1; } sb.append(path.substring(currentChar, path.length())); XPath xpath; try { xpath = XPath.newInstance(sb.toString()); xpath.addNamespace(NS_PREFIX, doc.getRootElement().getNamespaceURI()); return xpath.selectNodes(doc); } catch (JDOMException e) { e.printStackTrace(); } return null; }
private List<Element> getBatchProcessPartElements() { Element batchProcessElement = document.getRootElement(); Filter<Element> filters = Filters.element(BATCH_PROCESS_PART); IteratorIterable<Element> batchProcessPartElement = batchProcessElement.getDescendants(filters); List<Element> batchProcessPartElements = IteratorUtils.toList(batchProcessPartElement); return batchProcessPartElements; }
@SuppressWarnings("deprecation") public void setItemDescription(String itemDescription) throws JDOMException, IOException, URISyntaxException { StringReader is = new StringReader(itemDescription); SAXBuilder sb = new SAXBuilder(); sb.setValidation(true); ClassLoader loader = Thread.currentThread().getContextClassLoader(); URL url = loader.getResource("../../xml/cloud.xsd"); File file = new File(url.toURI()); if (file != null) { sb.setProperty( "http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema"); sb.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource", file); } Document dDoc = sb.build(is); Element dDocElm = dDoc.getRootElement().clone(); this.descElm.removeContent(); this.descElm.addContent(dDocElm); }
public void parseDoc(File file) throws Exception { adjustFile(file); start = -1; end = -1; prevValue = -1; ocrAl = new ArrayList<>(1000); outFileName = file.getAbsolutePath().substring(0, file.getAbsolutePath().length() - 4) + "ngt.xml"; builder = new SAXBuilder(); doc = builder.build(file); root = doc.getRootElement(); xmlns = root.getNamespace(); xpath = XPathFactory.instance() .compile( "//ns:span[@class='ocr_word']", Filters.element(), null, Namespace.getNamespace("ns", "http://www.w3.org/1999/xhtml")); List<Element> elements = xpath.evaluate(root); for (Element element : elements) { parseOcrWord(element); } ocrAl.add("%%%"); ocrAl.add("%%%"); findAnchors(); writeFragment(start, end); }
/* <fnmocTable> <entry> <grib1Id>0004</grib1Id> <fnmocId>0004</fnmocId> <name>MISC_GRIDS</name> <fullName>Miscellaneous Grids</fullName> <description>atmospheric model</description> <status>current</status> </entry> <entry> <grib1Id>0008</grib1Id> <fnmocId>0008</fnmocId> <name>STRATO</name> <fullName>NOGAPS Stratosphere Functions</fullName> <description>atmospheric stratosphere model</description> <status>current</status> </entry> */ private Map<Integer, String> readGenProcess(String path) { try (InputStream is = GribResourceReader.getInputStream(path)) { if (is == null) { logger.error("Cant find FNMOC gen process table = " + path); return null; } SAXBuilder builder = new SAXBuilder(); org.jdom2.Document doc = builder.build(is); Element root = doc.getRootElement(); Map<Integer, String> result = new HashMap<>(200); Element fnmocTable = root.getChild("fnmocTable"); List<Element> params = fnmocTable.getChildren("entry"); for (Element elem1 : params) { int code = Integer.parseInt(elem1.getChildText("grib1Id")); String desc = elem1.getChildText("fullName"); result.put(code, desc); } return Collections.unmodifiableMap(result); // all at once - thread safe } catch (IOException ioe) { logger.error("Cant read FNMOC Table 1 = " + path, ioe); } catch (JDOMException e) { logger.error("Cant parse FNMOC Table 1 = " + path, e); } return null; }
public void scrollTo(Deque<ElementPosition> nodeChain) { if (currentEditor.getValue().getMediaType().equals(MediaType.XHTML)) { XHTMLCodeEditor xhtmlCodeEditor = (XHTMLCodeEditor) currentEditor.getValue(); String code = xhtmlCodeEditor.getCode(); /* int index = code.indexOf(html); logger.info("index of clicked html " + index + " html: " + html); xhtmlCodeEditor.scrollTo(index);*/ LocatedJDOMFactory factory = new LocatedJDOMFactory(); try { org.jdom2.Document document = XHTMLUtils.parseXHTMLDocument(code, factory); org.jdom2.Element currentElement = document.getRootElement(); ElementPosition currentElementPosition = nodeChain.pop(); while (currentElementPosition != null) { IteratorIterable<org.jdom2.Element> children; if (StringUtils.isNotEmpty(currentElementPosition.getNamespaceUri())) { List<Namespace> namespaces = currentElement.getNamespacesInScope(); Namespace currentNamespace = null; for (Namespace namespace : namespaces) { if (namespace.getURI().equals(currentElementPosition.getNamespaceUri())) { currentNamespace = namespace; break; } } Filter<org.jdom2.Element> filter = Filters.element(currentElementPosition.getNodeName(), currentNamespace); children = currentElement.getDescendants(filter); } else { Filter<org.jdom2.Element> filter = Filters.element(currentElementPosition.getNodeName()); children = currentElement.getDescendants(filter); } int currentNumber = 0; for (org.jdom2.Element child : children) { if (currentNumber == currentElementPosition.getPosition()) { currentElement = child; break; } currentNumber++; } try { currentElementPosition = nodeChain.pop(); } catch (NoSuchElementException e) { logger.info("no more element in node chain"); currentElementPosition = null; } } LocatedElement locatedElement = (LocatedElement) currentElement; EditorPosition pos = new EditorPosition(locatedElement.getLine() - 1, locatedElement.getColumn()); logger.info("pos for scrolling to is " + pos.toJson()); xhtmlCodeEditor.scrollTo(pos); } catch (IOException | JDOMException e) { logger.error("", e); } } }
public WireFeed parse(Document document, boolean validate) throws IllegalArgumentException, FeedException { if (validate) { validateFeed(document); } Element rssRoot = document.getRootElement(); return parseFeed(rssRoot); }
public void markHasDone(String computerName, List<String> recordsWithErrors) throws ComputerNotFound { Element batchProcessElement = document.getRootElement(); removeBatchPartFromDocument(computerName); Element errorsElement = batchProcessElement.getChild(ERRORS); addErrorsToDocument(recordsWithErrors, errorsElement); }
@Override public WireFeed parse(final Document document, final boolean validate, final Locale locale) throws IllegalArgumentException, FeedException { if (validate) { validateFeed(document); } final Element rssRoot = document.getRootElement(); return parseFeed(rssRoot, locale); }
/** * Creates an XML document (JDOM) for the given feed bean. * * <p> * * @param feed the feed bean to generate the XML document from. * @return the generated XML document (JDOM). * @throws IllegalArgumentException thrown if the type of the given feed bean does not match with * the type of the WireFeedGenerator. * @throws FeedException thrown if the XML Document could not be created. */ @Override public Document generate(final WireFeed feed) throws IllegalArgumentException, FeedException { Document retValue; retValue = super.generate(feed); retValue.getRootElement().setAttribute("version", "2.0"); return retValue; }
TeamInfo readTeamXmlFile(final File teamFile) { try { Document doc = readFile(teamFile); return readTeamXml(doc.getRootElement()); } catch (Exception ex) { Logger.getLogger(XmlDataStore.class.getName()).log(Level.SEVERE, null, ex); } return null; }
MatchInfo readMatchXmlFile(final List<TeamInfo> teamCache, final File matchFile) { try { Document doc = readFile(matchFile); return readMatchXml(teamCache, doc.getRootElement()); } catch (Exception ex) { Logger.getLogger(XmlDataStore.class.getName()).log(Level.SEVERE, null, ex); } return null; }
@Test public final void testCleanupUnsetValues() { try { request = new SoapRequest("getAdMedium"); } catch (Exception e) { Assert.fail(e.getMessage()); } Assert.assertNotNull(request); Assert.assertNotNull(request.getDocument()); request.setValue("//ns:admediumId", "3096"); Document document = request.getDocument(); Namespace namespace = Namespace.getNamespace("ns", "http://api.zanox.com/namespace/2011-03-01/"); document.getRootElement().addNamespaceDeclaration(namespace); XPathFactory xpfac = XPathFactory.instance(); XPathExpression xp = xpfac.compile( "//ns:adspaceId", Filters.element(), null, document.getRootElement().getNamespacesInScope()); List<Element> elements = xp.evaluate(document); Assert.assertNotNull("Result is null.", elements); Assert.assertTrue( "There should be at least the ns:adspaceId node in elements.", elements.size() == 1); Assert.assertTrue( "The text of the element should be '?'", elements.get(0).getText().toString().equals("?")); request.cleanupUnsetValues(); elements = xp.evaluate(document); Assert.assertNotNull("Result is null.", elements); Assert.assertTrue( "There should be at least the ns:adspaceId node in elements.", elements.size() == 0); }
public static Question[] getQuestions(File xmlFile) { SAXBuilder builder = new SAXBuilder(); Question[] res = {}; try { Document document = (Document) builder.build(xmlFile); Element rootNode = document.getRootElement(); List topics = rootNode.getChildren("t"); String id, group, text, text_en, answer, q_type, q_ans, support, number; // , snippet; for (int i = 0; i < topics.size(); i++) { Element t = (Element) topics.get(i); List questions = t.getChildren("q"); for (int j = 0; j < questions.size(); j++) { Element q = (Element) questions.get(j); id = q.getAttributeValue("q_id").toString(); q_type = q.getAttributeValue("q_type").toString(); q_ans = q.getAttributeValue("q_exp_ans_type").toString(); support = q.getChild("answer").getAttributeValue("a_support"); // snippet = q.getChild("answer").getAttributeValue("a_support"); group = t.getAttributeValue("t_string").toString(); text = q.getChild("question").getText(); number = q.getChild("question").getAttributeValue("question_id"); answer = q.getChild("answer").getChildText("a_string"); text_en = q.getChild("q_translation").getText(); res = ArrayUtils.add( res, new Question( id, group, text, answer, text_en, new String[0], q_type, q_ans, support, number)); } } } catch (IOException io) { System.out.println(io.getMessage()); } catch (JDOMException jdomex) { System.out.println(jdomex.getMessage()); } return res; }