Java Code Examples for org.jdom2.Element#detach()

The following examples show how to use org.jdom2.Element#detach() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
/**
 * Output xml
 * @param eRoot - the root element
 * @param lang - the language which should be filtered or null for no filter
 * @return a string representation of the XML
 * @throws IOException
 */
private static String writeXML(Element eRoot, String lang) throws IOException {
    StringWriter sw = new StringWriter();
    if (lang != null) {
        // <label xml:lang="en" text="part" />
        XPathExpression<Element> xpE = XPathFactory.instance().compile("//label[@xml:lang!='" + lang + "']",
            Filters.element(), null, Namespace.XML_NAMESPACE);
        for (Element e : xpE.evaluate(eRoot)) {
            e.getParentElement().removeContent(e);
        }
    }
    XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat());
    Document docOut = new Document(eRoot.detach());
    xout.output(docOut, sw);
    return sw.toString();
}
 
Example 2
private void filterNonEmpty(String classId, Element e) {
    SolrClient solrClient = MCRSolrClientFactory.getMainSolrClient();
    Element[] categories = e.getChildren("category").toArray(Element[]::new);
    for (Element cat : categories) {
        SolrQuery solrQquery = new SolrQuery();
        solrQquery.setQuery(
            "category:\"" + MCRSolrUtils.escapeSearchValue(classId + ":" + cat.getAttributeValue("ID")) + "\"");
        solrQquery.setRows(0);
        try {
            QueryResponse response = solrClient.query(solrQquery);
            SolrDocumentList solrResults = response.getResults();
            if (solrResults.getNumFound() == 0) {
                cat.detach();
            } else {
                filterNonEmpty(classId, cat);
            }
        } catch (SolrServerException | IOException exc) {
            LOGGER.error(exc);
        }

    }
}
 
Example 3
public String checkDataSubTag(Element datasubtag) {
    Element[] children = datasubtag.getChildren("text").toArray(Element[]::new);
    int textCount = children.length;
    for (int i = 0; i < children.length; i++) {
        Element child = children[i];
        String text = child.getTextTrim();
        if (text == null || text.length() == 0) {
            child.detach();
            textCount--;
            continue;
        }
        if (child.getAttribute("lang") != null) {
            child.getAttribute("lang").setNamespace(XML_NAMESPACE);
            LOGGER.warn("namespace add for xml:lang attribute in {}", datasubtag.getName());
        }
    }
    if (textCount == 0) {
        return "history date is empty";
    }
    return checkMetaObjectWithLang(datasubtag, MCRMetaHistoryDate.class);
}
 
Example 4
@Test
public void testXPath() {
    Element root = new Element("root");
    Element title1 = new Element("title");
    Element title2 = new Element("title");
    Element author = new Element("contributor");
    Attribute role = new Attribute("role", "author");
    Attribute lang = new Attribute("lang", "de", Namespace.XML_NAMESPACE);
    author.setAttribute(role);
    author.setAttribute(lang);
    root.addContent(title1);
    root.addContent(author);
    root.addContent(title2);
    new Document(root);

    assertEquals("/root", MCRXPathBuilder.buildXPath(root));
    assertEquals("/root/contributor", MCRXPathBuilder.buildXPath(author));
    assertEquals("/root/title", MCRXPathBuilder.buildXPath(title1));
    assertEquals("/root/title[2]", MCRXPathBuilder.buildXPath(title2));
    assertEquals("/root/contributor/@role", MCRXPathBuilder.buildXPath(role));
    assertEquals("/root/contributor/@xml:lang", MCRXPathBuilder.buildXPath(lang));

    root.detach();
    assertEquals("root", MCRXPathBuilder.buildXPath(root));
    assertEquals("root/contributor", MCRXPathBuilder.buildXPath(author));
}
 
Example 5
/**
 * Removes additional XML data from this node.
 *
 * @param dataName
 *            the name of the additional XML data element to be removed
 * @throws IOException
 *             if the XML data can not be retrieved
 * @throws JDOMException
 *             if the XML data can not be parsed
 */
public void removeAdditionalData(String dataName) throws IOException, JDOMException {
    MCRFile dataFile = MCRFile.getRootFile(id);
    if (dataFile == null) {
        return;
    }
    Document doc = dataFile.getContentAsJDOM();
    Element child = doc.getRootElement().getChild(dataName);
    if (child != null) {
        child.detach();
    }
    if (doc.getRootElement().getChildren().size() == 0) {
        dataFile.delete();
    } else {
        dataFile.setContentFrom(doc);
    }
}
 
Example 6
Source Project: rome   File: Atom10Parser.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Parse entry from reader.
 */
public static Entry parseEntry(final Reader rd, final String baseURI, final Locale locale) throws JDOMException, IOException, IllegalArgumentException,
        FeedException {

    // Parse entry into JDOM tree
    final SAXBuilder builder = new SAXBuilder();
    final Document entryDoc = builder.build(rd);
    final Element fetchedEntryElement = entryDoc.getRootElement();
    fetchedEntryElement.detach();

    // Put entry into a JDOM document with 'feed' root so that Rome can
    // handle it
    final Feed feed = new Feed();
    feed.setFeedType("atom_1.0");
    final WireFeedOutput wireFeedOutput = new WireFeedOutput();
    final Document feedDoc = wireFeedOutput.outputJDom(feed);
    feedDoc.getRootElement().addContent(fetchedEntryElement);

    if (baseURI != null) {
        feedDoc.getRootElement().setAttribute("base", baseURI, Namespace.XML_NAMESPACE);
    }

    final WireFeedInput input = new WireFeedInput(false, locale);
    final Feed parsedFeed = (Feed) input.build(feedDoc);
    return parsedFeed.getEntries().get(0);
}
 
Example 7
Source Project: rome   File: BaseWireFeedParser.java    License: Apache License 2.0 6 votes vote down vote up
protected List<Element> extractForeignMarkup(final Element e, final Extendable ext, final Namespace namespace) {

        final ArrayList<Element> foreignElements = new ArrayList<Element>();

        for (final Element element : e.getChildren()) {
            if (!namespace.equals(element.getNamespace()) && ext.getModule(element.getNamespaceURI()) == null) {
                // if element not in the RSS namespace and elem was not handled by a module save it
                // as foreign markup but we can't detach it while we're iterating
                foreignElements.add(element.clone());
            }
        }

        // now we can detach the foreign markup elements
        for (final Element foreignElement : foreignElements) {
            foreignElement.detach();
        }

        return foreignElements;

    }
 
Example 8
@Override
public Object sendIospMessage(Object message) {
  if (message instanceof Element) {
    iospParam = (Element) message;
    iospParam.detach();
    return true;
  }

  return super.sendIospMessage(message);
}
 
Example 9
public void removeElements(String xPath) {
    Iterator<Element> selected;
    try {
        selected = buildXPath(xPath).evaluate(getMODS()).iterator();
    } catch (JDOMException ex) {
        String msg = "Could not remove elements at " + xPath;
        throw new MCRException(msg, ex);
    }

    while (selected.hasNext()) {
        Element element = selected.next();
        element.detach();
    }
}
 
Example 10
private void removeSourceExtension(Element resultingMODS) {
    for (Element extension : resultingMODS.getChildren("extension", MCRConstants.MODS_NAMESPACE)) {
        for (Element source : extension.getChildren("source")) {
            source.detach();
        }
        if (extension.getChildren().isEmpty()) {
            extension.detach();
        }
    }
}
 
Example 11
private void sort(List<Element> list, Comparator<Element> c) {
    Element[] a = list.toArray(new Element[list.size()]);
    Arrays.sort(a, c);
    for (Element element : a) {
        element.detach();
    }
    Collections.addAll(list, a);
}
 
Example 12
Source Project: iaf   File: XmlBuilder.java    License: Apache License 2.0 5 votes vote down vote up
private Element buildElement(String value)
		throws JDOMException, IOException {
	StringReader stringReader = new StringReader(value);
	SAXBuilder saxBuilder = new SAXBuilder();
	Document document;
	document = saxBuilder.build(stringReader);
	Element element = document.getRootElement();
	return element.detach();
}
 
Example 13
public DatasetScanConfig readDatasetScanConfig(Element dsElem) {
  DatasetScanConfig result = new DatasetScanConfig();

  result.name = dsElem.getAttributeValue("name");
  result.path = StringUtil2.trim(dsElem.getAttributeValue("path"), '/');
  if (result.path == null) {
    errlog.format("ERROR: must specify path attribute.%n");
    fatalError = true;
  }

  String scanDir = dsElem.getAttributeValue("location");
  if (scanDir == null) {
    errlog.format("ERROR: must specify directory root in location attribute.%n");
    fatalError = true;
  } else {
    result.scanDir = AliasTranslator.translateAlias(scanDir);
    File scanFile = new File(result.scanDir);
    if (!scanFile.exists()) {
      errlog.format("ERROR: directory %s does not exist%n", result.scanDir);
      fatalError = true;
    }
  }

  result.restrictAccess = dsElem.getAttributeValue("restrictAccess");

  // look for ncml
  Element ncmlElem = dsElem.getChild("netcdf", Catalog.defNS);
  if (ncmlElem != null) {
    ncmlElem.detach();
    result.ncmlElement = ncmlElem;
  }

  // Read filter element
  Element filterElem = dsElem.getChild("filter", Catalog.defNS);
  result.filters = readDatasetScanFilter(filterElem);

  // Read namer element
  Element namerElem = dsElem.getChild("namer", Catalog.defNS);
  result.namers = readDatasetScanNamer(namerElem);

  // Read filesSort or sort element
  Element filesSortElem = dsElem.getChild("filesSort", Catalog.defNS);
  if (filesSortElem != null)
    result.isSortIncreasing = readFilesSort(filesSortElem);
  Element sorterElem = dsElem.getChild("sort", Catalog.defNS);
  if (!result.isSortIncreasing.isPresent() && sorterElem != null)
    result.isSortIncreasing = readSort(sorterElem);

  // Deal with latest
  String addLatestAttribute = dsElem.getAttributeValue("addLatest");
  Element addLatestElem = dsElem.getChild("addLatest", Catalog.defNS); // not in docs
  Element addProxiesElem = dsElem.getChild("addProxies", Catalog.defNS);
  result.addLatest = readDatasetScanAddProxies(addProxiesElem, addLatestElem, addLatestAttribute);

  /*
   * Read addDatasetSize element.
   * Element addDsSizeElem = dsElem.getChild("addDatasetSize", Catalog.defNS);
   * if (addDsSizeElem != null) { // docs: default true
   * if (addDsSizeElem.getTextNormalize().equalsIgnoreCase("false"))
   * result.addDatasetSize = false;
   * }
   */

  // Read addTimeCoverage element.
  Element addTimeCovElem = dsElem.getChild("addTimeCoverage", Catalog.defNS);
  if (addTimeCovElem != null) {
    result.addTimeCoverage = readDatasetScanAddTimeCoverage(addTimeCovElem);
  }

  return result;
}
 
Example 14
public static MCRChangeData remove(Element element) {
    Element parent = element.getParentElement();
    MCRChangeData data = new MCRChangeData("removed-element", element, parent.indexOf(element), parent);
    element.detach();
    return data;
}
 
Example 15
/**
 * Build MCRQuery from editor XML input
 */
public static MCRQuery buildFormQuery(Element root) {
    Element conditions = root.getChild("conditions");

    if (conditions.getAttributeValue("format", "xml").equals("xml")) {
        Element condition = conditions.getChildren().get(0);
        renameElements(condition);

        // Remove conditions without values
        List<Element> empty = new ArrayList<>();
        for (Iterator<Element> it = conditions.getDescendants(new ElementFilter("condition")); it.hasNext();) {
            Element cond = it.next();
            if (cond.getAttribute("value") == null) {
                empty.add(cond);
            }
        }

        // Remove empty sort conditions
        Element sortBy = root.getChild("sortBy");
        if (sortBy != null) {
            for (Element field : sortBy.getChildren("field")) {
                if (field.getAttributeValue("name", "").length() == 0) {
                    empty.add(field);
                }
            }
        }

        for (int i = empty.size() - 1; i >= 0; i--) {
            empty.get(i).detach();
        }

        if (sortBy != null && sortBy.getChildren().size() == 0) {
            sortBy.detach();
        }

        // Remove empty returnFields
        Element returnFields = root.getChild("returnFields");
        if (returnFields != null && returnFields.getText().length() == 0) {
            returnFields.detach();
        }
    }

    return MCRQuery.parseXML(root.getDocument());
}
 
Example 16
/**
 * Writes an NcML element to a Writer.
 *
 * @param elem an NcML element.
 * @param writer the Writer to write the NcML document to. Will be closed at end of the method.
 * @throws IOException if there's any problem writing.
 */
public void writeToWriter(Element elem, Writer writer) throws IOException {
  xmlOutputter.setFormat(xmlFormat);
  elem.detach(); // In case this element had previously been added to a Document.
  xmlOutputter.output(new Document(elem), writer);
}
 
Example 17
/**
 * Writes an NcML element to a Writer.
 *
 * @param elem an NcML element.
 * @param writer the Writer to write the NcML document to. Will be closed at end of the method.
 * @throws IOException if there's any problem writing.
 */
public void writeToWriter(Element elem, Writer writer) throws IOException {
  xmlOutputter.setFormat(xmlFormat);
  elem.detach(); // In case this element had previously been added to a Document.
  xmlOutputter.output(new Document(elem), writer);
}