org.jdom2.Element.getChildren()方法的使用及代码示例

x33g5p2x  于2022-01-19 转载在 其他  
字(13.3k)|赞(0)|评价(0)|浏览(105)

本文整理了Java中org.jdom2.Element.getChildren()方法的一些代码示例,展示了Element.getChildren()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Element.getChildren()方法的具体详情如下:
包路径:org.jdom2.Element
类名称:Element
方法名:getChildren

Element.getChildren介绍

[英]This returns a List of all the child elements nested directly (one level deep) within this element, as Element objects. If this target element has no nested elements, an empty List is returned. The returned list is "live" in document order and changes to it affect the element's actual contents.

Sequential traversal through the List is best done with a Iterator since the underlying implement of List.size() may not be the most efficient.

No recursion is performed, so elements nested two levels deep would have to be obtained with:

Iterator itr = (currentElement.getChildren()).iterator(); 
while(itr.hasNext()) { 
Element oneLevelDeep = (Element)itr.next(); 
List twoLevelsDeep = oneLevelDeep.getChildren(); 
// Do something with these children 
}

[中]这将返回直接嵌套在该元素中的所有子元素的List,作为Element对象。如果此目标元素没有嵌套元素,则返回空列表。返回的列表在文档顺序中是“活动”的,对它的更改会影响元素的实际内容。
通过列表的顺序遍历最好使用迭代器完成,因为列表的底层实现是这样的。size()可能不是最有效的。
不执行递归,因此嵌套在两层深处的元素必须通过以下方式获得:

Iterator itr = (currentElement.getChildren()).iterator(); 
while(itr.hasNext()) { 
Element oneLevelDeep = (Element)itr.next(); 
List twoLevelsDeep = oneLevelDeep.getChildren(); 
// Do something with these children 
}

代码示例

代码示例来源:origin: com.thoughtworks.xstream/xstream

protected int getChildCount() {
  return currentElement.getChildren().size();
}

代码示例来源:origin: com.thoughtworks.xstream/xstream

protected Object getChild(int index) {
  return currentElement.getChildren().get(index);
}

代码示例来源:origin: gocd/gocd

private List<File> parseFiles(Element filesElement, String fileType) {
  List files = filesElement.getChild(fileType).getChildren("file");
  List<File> modifiedFiles = new ArrayList<>();
  for (Iterator iterator = files.iterator(); iterator.hasNext();) {
    Element node = (Element) iterator.next();
    modifiedFiles.add(new File(org.apache.commons.lang3.StringEscapeUtils.unescapeXml(node.getText())));
  }
  return modifiedFiles;
}

代码示例来源:origin: com.cerner.ccl.whitenoise/whitenoise-rules-core

private String getSizeFunctionOptionNumber(final Element sizeFunction) {
  if (sizeFunction.getChildren().size() < 3) {
    return "1";
  }
  // The the second param should store the contents of the size function option number
  final Element secondParam = sizeFunction.getChildren().get(2);
  return secondParam.getAttributeValue("text");
}

代码示例来源:origin: org.apache.ctakes/ctakes-relation-extractor

private static Element getSingleChild(Element elem, String elemName, String causeID) {
 List<Element> children = elem.getChildren(elemName);
 if (children.size() != 1) {
  error(String.format("not exactly one '%s' child", elemName), causeID);
 }
 return children.size() > 0 ? children.get(0) : null;
}

代码示例来源:origin: gocd/gocd

@Test
public void shouldListAllArtifactsWhenArtifactsNotPurged() throws Exception {
  HtmlRenderer renderer = new HtmlRenderer("context");
  DirectoryEntries directoryEntries = new DirectoryEntries();
  directoryEntries.add(new FolderDirectoryEntry("cruise-output", "", new DirectoryEntries()));
  directoryEntries.add(new FolderDirectoryEntry("some-artifact", "", new DirectoryEntries()));
  directoryEntries.render(renderer);
  Element document = getRenderedDocument(renderer);
  assertThat(document.getChildren().size(), is(2));
  Element cruiseOutputElement = (Element) document.getChildren().get(0);
  assertThat(cruiseOutputElement.getChild("div").getChild("span").getChild("a").getTextNormalize(), is("cruise-output"));
  Element artifactElement = (Element) document.getChildren().get(1);
  assertThat(artifactElement.getChild("div").getChild("span").getChild("a").getTextNormalize(), is("some-artifact"));
}

代码示例来源:origin: rometools/rome

/**
 * @param e element to parse
 * @param md metadata to fill in
 */
private void parseScenes(final Element e, final Metadata md) {
  final Element scenesElement = e.getChild("scenes", getNS());
  if (scenesElement != null) {
    final List<Element> sceneElements = scenesElement.getChildren("scene", getNS());
    final Scene[] scenes = new Scene[sceneElements.size()];
    for (int i = 0; i < sceneElements.size(); i++) {
      scenes[i] = new Scene();
      scenes[i].setTitle(sceneElements.get(i).getChildText("sceneTitle", getNS()));
      scenes[i].setDescription(sceneElements.get(i).getChildText("sceneDescription", getNS()));
      final String sceneStartTime = sceneElements.get(i).getChildText("sceneStartTime", getNS());
      if (sceneStartTime != null) {
        scenes[i].setStartTime(new Time(sceneStartTime));
      }
      final String sceneEndTime = sceneElements.get(i).getChildText("sceneEndTime", getNS());
      if (sceneEndTime != null) {
        scenes[i].setEndTime(new Time(sceneEndTime));
      }
    }
    md.setScenes(scenes);
  }
}

代码示例来源:origin: sc.fiji/TrackMate_

/**
 * Read and return the list of track indices that define the filtered track
 * collection.
 */
private Set< Integer > readFilteredTrackIDs()
{
  final Element filteredTracksElement = root.getChild( FILTERED_TRACK_ELEMENT_KEY_v12 );
  if ( null == filteredTracksElement ) { return null; }
  // Work because the track splitting from the graph is deterministic
  final List< Element > elements = filteredTracksElement.getChildren( TRACK_ID_ELEMENT_KEY_v12 );
  final HashSet< Integer > filteredTrackIndices = new HashSet< >( elements.size() );
  for ( final Element indexElement : elements )
  {
    final int trackID = readIntAttribute( indexElement, TRACK_ID_ATTRIBUTE_NAME_v12, logger );
    filteredTrackIndices.add( trackID );
  }
  return filteredTrackIndices;
}

代码示例来源:origin: org.mycore/mycore-xeditor

private void handleInclude(Element container, Element includeRule) {
  boolean modified = handleBeforeAfter(container, includeRule, ATTR_BEFORE, 0, 0);
  if (!modified) {
    includeRule.setAttribute(ATTR_AFTER, includeRule.getAttributeValue(ATTR_AFTER, "*"));
    handleBeforeAfter(container, includeRule, ATTR_AFTER, 1, container.getChildren().size());
  }
}

代码示例来源:origin: Unidata/thredds

public int makeBmtTable(List<Element> featureCatList) {
 int count = 0;
 for (Element featureCat : featureCatList) {
  List<Element> featureCollectList = featureCat.getChildren("featureCollection");
  count += featureCollectList.size();
  for (Element featureCollect : featureCollectList) {
   int f = Integer.parseInt(featureCollect.getChildText("F"));
   int x = Integer.parseInt(featureCollect.getChildText("X"));
   int y = Integer.parseInt(featureCollect.getChildText("Y"));
   String name = featureCollect.getChild("annotation").getChildTextNormalize("documentation");
   int fxy = (f << 16) + (x << 8) + y;
   Sequence seq = new Sequence(x, y, name);
   bmTable.put(fxy, seq);
   List<Element> features = featureCollect.getChildren("feature");
   for (Element feature : features) {
    f = Integer.parseInt(feature.getChildText("F"));
    x = Integer.parseInt(feature.getChildText("X"));
    y = Integer.parseInt(feature.getChildText("Y"));
    name = feature.getChild("annotation").getChildTextNormalize("documentation");
    fxy = (f << 16) + (x << 8) + y;
    Feature feat = new Feature(fxy, name);
    seq.features.add(feat); 
   }
  }
 }
 return count;
}

代码示例来源:origin: pwm-project/pwm

public X509CertificateValue fromXmlElement( final PwmSetting pwmSetting, final Element settingElement, final PwmSecurityKey key )
{
  final List<X509Certificate> certificates = new ArrayList<>();
  final List<Element> valueElements = settingElement.getChildren( "value" );
  for ( final Element loopValueElement : valueElements )
  {
    final String b64encodedStr = loopValueElement.getText();
    try
    {
      certificates.add( X509Utils.certificateFromBase64( b64encodedStr ) );
    }
    catch ( Exception e )
    {
      LOGGER.error( "error decoding certificate: " + e.getMessage() );
    }
  }
  return new X509CertificateValue( certificates.toArray( new X509Certificate[ certificates.size() ] ) );
}

代码示例来源:origin: gocd/gocd

public CommandSnippet parse(String xmlContent, String fileName, String relativeFilePath) {
  try {
    Document document = buildXmlDocument(xmlContent, CommandSnippet.class.getResource("command-snippet.xsd"));
    CommandSnippetComment comment = getComment(document);
    Element execTag = document.getRootElement();
    String commandName = execTag.getAttributeValue("command");
    List<String> arguments = new ArrayList<>();
    for (Object child : execTag.getChildren()) {
      Element element = (Element) child;
      arguments.add(element.getValue());
    }
    return new CommandSnippet(commandName, arguments, comment, fileName, relativeFilePath);
  } catch (Exception e) {
    String errorMessage = String.format("Reason: %s", e.getMessage());
    LOGGER.info("Could not load command '{}'. {}", fileName, errorMessage);
    return CommandSnippet.invalid(fileName, errorMessage, new EmptySnippetComment());
  }
}

代码示例来源:origin: gocd/gocd

public HashMap<String, String> parseInfoToGetUUID(String output, String queryURL, SAXBuilder builder) {
  HashMap<String, String> uidToUrlMap = new HashMap<>();
  try {
    Document document = builder.build(new StringReader(output));
    Element root = document.getRootElement();
    List<Element> entries = root.getChildren("entry");
    for (Element entry : entries) {
      uidToUrlMap.put(queryURL, entry.getChild("repository").getChild("uuid").getValue());
    }
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
  return uidToUrlMap;
}

代码示例来源:origin: gocd/gocd

private Modification parseLogEntry(Element logEntry, String path) throws ParseException {
  Element logEntryPaths = logEntry.getChild("paths");
  if (logEntryPaths == null) {
    /* Path-based access control forbids us from learning
     * details of this log entry, so skip it. */
    return null;
  }
  Date modifiedTime = convertDate(logEntry.getChildText("date"));
  String author = logEntry.getChildText("author");
  String comment = logEntry.getChildText("msg");
  String revision = logEntry.getAttributeValue("revision");
  Modification modification = new Modification(author, comment, null, modifiedTime, revision);
  List paths = logEntryPaths.getChildren("path");
  for (Iterator iterator = paths.iterator(); iterator.hasNext();) {
    Element node = (Element) iterator.next();
    if (underPath(path, node.getText())) {
      ModifiedAction action = convertAction(node.getAttributeValue("action"));
      modification.createModifiedFile(node.getText(), null, action);
    }
  }
  return modification;
}

代码示例来源:origin: geotools/geotools

public void assignTo(Element element) {
  if (!element.getName().equals(GeoTiffConstants.GEOTIFF_IIO_ROOT_ELEMENT_NAME)) {
    throw new IllegalArgumentException(
        "root not found: " + GeoTiffConstants.GEOTIFF_IIO_ROOT_ELEMENT_NAME);
  }
  final Element ifd1 = element.getChild(GeoTiffConstants.GEOTIFF_IFD_TAG);
  if (ifd1 == null) {
    throw new IllegalArgumentException(
        "Unable to find child " + GeoTiffConstants.GEOTIFF_IFD_TAG);
  }
  final Element ifd2 = createIFD();
  ifd1.setAttribute(
      GeoTiffConstants.GEOTIFF_TAGSETS_ATT_NAME,
      ifd2.getAttributeValue(GeoTiffConstants.GEOTIFF_TAGSETS_ATT_NAME));
  final Element[] childElems = (Element[]) ifd2.getChildren().toArray(new Element[0]);
  for (int i = 0; i < childElems.length; i++) {
    final Element child = childElems[i];
    ifd2.removeContent(child);
    ifd1.addContent(child);
  }
}

代码示例来源:origin: pwm-project/pwm

public NumericArrayValue fromXmlElement( final PwmSetting pwmSetting, final Element settingElement, final PwmSecurityKey input )
  {
    final List<Long> returnList = new ArrayList<>(  );
    final List<Element> valueElements = settingElement.getChildren( "value" );
    for ( final Element element : valueElements )
    {
      final String strValue = element.getText();
      final Long longValue = Long.parseLong( strValue );
      returnList.add( longValue );
    }
    return new NumericArrayValue( returnList );
  }
};

代码示例来源:origin: pwm-project/pwm

public LocalizedStringValue fromXmlElement( final PwmSetting pwmSetting, final Element settingElement, final PwmSecurityKey key )
  {
    final List elements = settingElement.getChildren( "value" );
    final Map<String, String> values = new TreeMap<>();
    for ( final Object loopValue : elements )
    {
      final Element loopValueElement = ( Element ) loopValue;
      final String localeString = loopValueElement.getAttributeValue( "locale" );
      final String value = loopValueElement.getText();
      values.put( localeString == null ? "" : localeString, value );
    }
    return new LocalizedStringValue( values );
  }
};

代码示例来源:origin: net.preibisch/multiview-reconstruction

public PointSpreadFunctions fromXml( final Element allPSFs, final File basePath ) throws SpimDataException
{
  final PointSpreadFunctions pointSpreadFunctions = super.fromXml( allPSFs );
  for ( final Element psfElement : allPSFs.getChildren( PSF_TAG ) )
  {
    final int tpId = Integer.parseInt( psfElement.getAttributeValue( PSF_TIMEPOINT_ATTRIBUTE_NAME ) );
    final int vsId = Integer.parseInt( psfElement.getAttributeValue( PSF_SETUP_ATTRIBUTE_NAME ) );
    final String file = psfElement.getChildText( PSF_FILE_TAG );
    pointSpreadFunctions.addPSF( new ViewId( tpId, vsId ), new PointSpreadFunction( basePath, file ) );
  }
  return pointSpreadFunctions;
}

代码示例来源:origin: Unidata/thredds

public List<String> getElementList(String elementName, String subElementName) {
 List<String> result = new ArrayList<>();
 Element elem = rootElem.getChild( elementName );
 if (elem == null) return result;
 List<Element> rootList = elem.getChildren(subElementName);
 for (Element elem2 : rootList) {
  String location = StringUtils.cleanPath(elem2.getTextNormalize());
  if (location.length() > 0)
   result.add(location);
 }
 return result;
}

代码示例来源:origin: Unidata/thredds

private void processSeq(Structure struct, Element parent) throws IOException {
 if (parent == null || struct == null) return;
 List<Variable> vars = struct.getVariables();
 for (Element child : parent.getChildren("fld", Catalog.ncmlNS)) {
  String idxS = child.getAttributeValue("idx");
  int idx = Integer.parseInt(idxS);
  if (idx < 0 || idx >= vars.size()) {
   log.error("Bad index = %s", child);
   continue;
  }
  Variable want = vars.get(idx);
  struct.removeMemberVariable(want);
  System.out.printf("removed %s%n", want);
 }
}

相关文章

微信公众号

最新文章

更多