本文整理汇总了Java中org.w3c.dom.Document.getDocumentElement方法的典型用法代码示例。如果您正苦于以下问题:Java Document.getDocumentElement方法的具体用法?Java Document.getDocumentElement怎么用?Java Document.getDocumentElement使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类org.w3c.dom.Document
的用法示例。
在下文中一共展示了Document.getDocumentElement方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: buildSingleMetadataResolver
import org.w3c.dom.Document; //导入方法依赖的package包/类
/**
* Build single metadata resolver.
*
* @param metadataFilterChain the metadata filters chained together
* @param resource the resource
* @param document the xml document to parse
* @return list of resolved metadata from resources.
* @throws IOException the iO exception
*/
private List<MetadataResolver> buildSingleMetadataResolver(final MetadataFilter metadataFilterChain,
final Resource resource, final Document document) throws IOException {
final List<MetadataResolver> resolvers = new ArrayList<>();
final Element metadataRoot = document.getDocumentElement();
final DOMMetadataResolver metadataProvider = new DOMMetadataResolver(metadataRoot);
metadataProvider.setParserPool(this.configBean.getParserPool());
metadataProvider.setFailFastInitialization(true);
metadataProvider.setRequireValidMetadata(this.requireValidMetadata);
metadataProvider.setId(metadataProvider.getClass().getCanonicalName());
if (metadataFilterChain != null) {
metadataProvider.setMetadataFilter(metadataFilterChain);
}
logger.debug("Initializing metadata resolver for [{}]", resource.getURL());
try {
metadataProvider.initialize();
} catch (final ComponentInitializationException ex) {
logger.warn("Could not initialize metadata resolver. Resource will be ignored", ex);
}
resolvers.add(metadataProvider);
return resolvers;
}
示例2: setValue
import org.w3c.dom.Document; //导入方法依赖的package包/类
@Override
public void setValue(Logger logger, PlanLoader<A> planLoader, Module<A> module) throws ParameterException, ConverterException, UnsupportedServiceException, SAXException, IOException, PlanException, URISyntaxException {
logger.config("setting XML value to module " + module.getPath() + ": '" + xmlValue + "'");
InputSource is = new InputSource(new StringReader(xmlValue));
Document doc = XMLUtils.docBuilder.parse(is);
Element elt = doc.getDocumentElement();
planLoader.setParam(elt, module);
}
示例3: test
import org.w3c.dom.Document; //导入方法依赖的package包/类
@Test
public void test() {
try {
FileInputStream fis = new FileInputStream(getClass().getResource("bug6690015.xml").getFile());
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(fis));
Element root = doc.getDocumentElement();
NodeList textnodes = root.getElementsByTagName("text");
int len = textnodes.getLength();
int index = 0;
int attindex = 0;
int attrlen = 0;
NamedNodeMap attrs = null;
while (index < len) {
Element te = (Element) textnodes.item(index);
attrs = te.getAttributes();
attrlen = attrs.getLength();
attindex = 0;
Node node = null;
while (attindex < attrlen) {
node = attrs.item(attindex);
System.out.println("attr: " + node.getNodeName() + " is shown holding value: " + node.getNodeValue());
attindex++;
}
index++;
System.out.println("-------------");
}
fis.close();
} catch (Exception e) {
Assert.fail("Exception: " + e.getMessage());
}
}
示例4: fillDOM
import org.w3c.dom.Document; //导入方法依赖的package包/类
@Override
protected void fillDOM(ModelContext ctx, Document doc) {
org.w3c.dom.Element root = doc.getDocumentElement();
for (String base : resourceBases) {
org.w3c.dom.Element baseElt = doc.createElement("resource-base");
baseElt.setTextContent(base);
root.appendChild(baseElt);
}
for (ConverterModel converter : converters) {
root.appendChild(converter.getDOM(doc));
}
}
示例5: OsgiDefaultsDefinition
import org.w3c.dom.Document; //导入方法依赖的package包/类
public OsgiDefaultsDefinition(Document document, ParserContext parserContext) {
Assert.notNull(document);
Element root = document.getDocumentElement();
ReferenceParsingUtil.checkAvailabilityAndCardinalityDuplication(root, DEFAULT_AVAILABILITY,
DEFAULT_CARDINALITY, parserContext);
parseDefaults(root, EGB_NS);
parseDefaults(root, SDM_NS);
}
示例6: addStylesheet
import org.w3c.dom.Document; //导入方法依赖的package包/类
private void addStylesheet(Document doc) {
for (Node node : XMLUtils.childrenNodes(doc)) {
if (node.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE) {
ProcessingInstruction pi = (ProcessingInstruction) node;
if (pi.getTarget().equals("xml-stylesheet")) {
return;
}
}
}
ProcessingInstruction stylesheetPI = doc.createProcessingInstruction("xml-stylesheet", "type=\"text/xsl\" href=\""+getURLBase()+"/static/style/alvisnlp-doc2xhtml.xslt\"");
Element root = doc.getDocumentElement();
doc.insertBefore(stylesheetPI, root);
}
示例7: loadTree
import org.w3c.dom.Document; //导入方法依赖的package包/类
@Override
public void loadTree(String xml) {
Document doc = XMLOperation.initTreeOp(xml);
Element rootElement = doc.getDocumentElement();
rotation = getAttribute(rootElement, "rotation");
AndroidTreeNode rootNode = new AndroidTreeNode(rootElement.getTagName());
rootNode.setAttribute("Location", xml);
loadNodes(rootElement, rootNode);
DefaultTreeModel newModel = new DefaultTreeModel(rootNode);
getTree().setModel(newModel);
}
示例8: getErrorsFromResponse
import org.w3c.dom.Document; //导入方法依赖的package包/类
private static List<String> getErrorsFromResponse(final byte[] serverResponse) {
final List<String> ret = new ArrayList<String>();
final InputStream is = new ByteArrayInputStream(serverResponse);
final Document doc;
try {
doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(is);
is.close();
}
catch (final Exception e) {
LOGGER.severe("Error analizando la respuesta del servidor: " + e); //$NON-NLS-1$
return Collections.singletonList(
"Error analizando la respuesta del servidor" //$NON-NLS-1$
);
}
final Node errorsNode = doc.getDocumentElement();
if (!"errors".equalsIgnoreCase(errorsNode.getNodeName())) { //$NON-NLS-1$
LOGGER.severe("La respuesta del servidor no contiene un nodo padre de errores"); //$NON-NLS-1$
return Collections.singletonList(
"La respuesta del servidor no contiene un nodo padre de errores" //$NON-NLS-1$
);
}
final NodeList childNodes = errorsNode.getChildNodes();
int idx = nextNodeElementIndex(childNodes, 0);
while (idx != -1) {
final Node errorItemNode = childNodes.item(idx);
ret.add(errorItemNode.getTextContent());
idx = nextNodeElementIndex(childNodes, idx + 1);
}
return ret;
}
示例9: getPlaylistMetadataFields
import org.w3c.dom.Document; //导入方法依赖的package包/类
/**
* gets the metadata fields for a playlist
*
* @param playlistIds the playlist's id (can be multiple ids)
* @return map of {playlistId -> map of the playlist metadata {fieldname -> value} }
* @throws IllegalArgumentException if playlistId is invalid
* @throws RuntimeException if error getting metadata
*/
protected Map<String, Map<String, String>> getPlaylistMetadataFields(String... playlistIds) {
if (log.isDebugEnabled()) log.debug("getPlaylistMetadataFields(playlistId="+Arrays.toString(playlistIds)+")");
HashMap<String, Map<String, String>> m;
if (playlistIds == null) {
throw new IllegalArgumentException("playlistIds must not be null or empty");
} else if (playlistIds.length == 0) {
m = new HashMap<String, Map<String, String>>(0);
} else {
m = new HashMap<String, Map<String, String>>(playlistIds.length);
Map<String, KalturaMetadata> metadataMap = getMetadataObjectsForKalturaPlaylistIds(playlistIds);
for (String playlistId : playlistIds) {
KalturaMetadata metadata = metadataMap.get(playlistId);
Map<String, String> fields = new LinkedHashMap<String, String>();
// if metadata exists for object
if (metadata != null) {
try {
Document metadataDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(new StringReader(metadata.xml)));
org.w3c.dom.Element root = metadataDoc.getDocumentElement();
NodeList childNodes = root.getChildNodes();
for (int i = 0; i < childNodes.getLength(); i++) {
Node node = childNodes.item(i);
if (node instanceof org.w3c.dom.Element) {
fields.put(node.getNodeName(), node.getTextContent());
}
}
fields = stripUnusedMetadataFields(fields, METADATA_PROFILE_NAME_PLAYLIST);
} catch (Exception e) {
throw new RuntimeException("Error getting metadata fields for kaltura playlist " + playlistIds + " :: " + e, e);
}
} else { // if no existing metadata then use default metadata
fields = initialMetadataFields.get(METADATA_PROFILE_NAME_PLAYLIST);
}
m.put(playlistId, fields);
}
}
return m;
}
示例10: parse
import org.w3c.dom.Document; //导入方法依赖的package包/类
private QueuePlacementPolicy parse(String str) throws Exception {
// Read and parse the allocations file.
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
.newInstance();
docBuilderFactory.setIgnoringComments(true);
DocumentBuilder builder = docBuilderFactory.newDocumentBuilder();
Document doc = builder.parse(IOUtils.toInputStream(str));
Element root = doc.getDocumentElement();
return QueuePlacementPolicy.fromXml(root, configuredQueues, conf);
}
示例11: checkSchema
import org.w3c.dom.Document; //导入方法依赖的package包/类
public static void checkSchema(Path solrSchemaPath, SchemaResponse response) throws IOException, SchemaValidationException {
// read the local schema.xml
final Document local;
try (InputStream xml = Files.newInputStream(solrSchemaPath, StandardOpenOption.READ)) {
final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
final DocumentBuilder builder = factory.newDocumentBuilder();
local = builder.parse(xml);
} catch (ParserConfigurationException | SAXException e) {
log.error("Error checking schema.xml: {}", e.getMessage(), e);
throw new IOException(e);
}
final SchemaRepresentation remote = response.getSchemaRepresentation();
final Element schema = local.getDocumentElement();
// check the field-types
final NodeList fieldTypes = schema.getElementsByTagName("fieldType");
final Set<String> fieldTypeNames = remote.getFieldTypes().stream()
.map(FieldTypeDefinition::getAttributes)
.map(m -> m.get("name"))
.filter(Objects::nonNull)
.map(String::valueOf)
.collect(Collectors.toSet());
for (int i = 0; i < fieldTypes.getLength(); i++) {
final Node fieldType = fieldTypes.item(i);
final String fieldTypeName = fieldType.getAttributes().getNamedItem("name").getNodeValue();
if (! fieldTypeNames.contains(fieldTypeName)) {
throw new SchemaValidationException(String.format("Missing <fieldType name='%s' />", fieldTypeName));
}
}
// TODO: check local -> remote.
}
示例12: getPrefices
import org.w3c.dom.Document; //导入方法依赖的package包/类
/**
* Returns an array of the legal metadataFormats for the specified host.
*
* @param baseURL DESCRIPTION
* @return The prefices value
* @exception Hexception DESCRIPTION
* @exception OAIErrorException DESCRIPTION
*/
private String[] getPrefices(String baseURL)
throws Hexception, OAIErrorException {
int ii;
String request = baseURL + "?verb=ListMetadataFormats";
if (msgHandler != null) {
msgHandler.statusMessage("A request for ListMetadataFormats has been made. Establishing connection with the data provider...");
}
Document doc = getDoc(request);
Element root = doc.getDocumentElement();
Element errele = findChild(root, "error");
if (errele != null) {
String oaiErrCode = errele.getAttribute("code");
String errMsg = getContent(errele);
if (errMsg == null) {
errMsg = "";
}
throw new OAIErrorException(oaiErrCode, getContent(errele));
}
Element verbele = mustFindChild(root, "ListMetadataFormats");
LinkedList reslist = new LinkedList();
Element pfxele = mustFindChild(verbele, "metadataFormat");
while (pfxele != null) {
Element pfxspec = mustFindChild(pfxele, "metadataPrefix");
reslist.add(getContent(pfxspec));
pfxele = findSibling(pfxele, "metadataFormat");
}
String[] prefices = new String[reslist.size()];
for (ii = 0; ii < prefices.length; ii++) {
String prefix = (String) reslist.get(ii);
prefices[ii] = prefix.replaceAll(":", "/");
if (bugs >= 1) {
prtln("prefix: \"" + prefices[ii] + "\"");
}
}
return prefices;
}
示例13: testCanonicalForm001
import org.w3c.dom.Document; //导入方法依赖的package包/类
/**
* Equivalence class partitioning with state and input values orientation
* for public void setParameter(String name, Object value) throws
* DOMException, <br>
* <b>pre-conditions</b>: the doc contains two subsequent processing
* instrictions, <br>
* <b>name</b>: canonical-form <br>
* <b>value</b>: true. <br>
* <b>Expected results</b>: the subsequent processing instrictions are
* separated with a single line break
*/
@Test
public void testCanonicalForm001() {
DOMImplementation domImpl = null;
try {
domImpl = DocumentBuilderFactory.newInstance().newDocumentBuilder().getDOMImplementation();
} catch (ParserConfigurationException pce) {
Assert.fail(pce.toString());
} catch (FactoryConfigurationError fce) {
Assert.fail(fce.toString());
}
Document doc = domImpl.createDocument("namespaceURI", "ns:root", null);
DOMConfiguration config = doc.getDomConfig();
Element root = doc.getDocumentElement();
ProcessingInstruction pi1 = doc.createProcessingInstruction("target1", "data1");
ProcessingInstruction pi2 = doc.createProcessingInstruction("target2", "data2");
root.appendChild(pi1);
root.appendChild(pi2);
if (!config.canSetParameter("canonical-form", Boolean.TRUE)) {
System.out.println("OK, setting 'canonical-form' to true is not supported");
return;
}
config.setParameter("canonical-form", Boolean.TRUE);
setHandler(doc);
doc.normalizeDocument();
Node child1 = root.getFirstChild();
Node child2 = child1.getNextSibling();
if (child2.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE) {
Assert.fail("the second child is expected to be a" + "single line break, returned: " + child2);
}
// return Status.passed("OK");
}
示例14: parseRequestBody
import org.w3c.dom.Document; //导入方法依赖的package包/类
/**
* Parse the request body
*
* @exception WebDAVServerException
*/
@Override
protected void parseRequestBody() throws WebDAVServerException
{
Document body = getRequestBodyAsDocument();
if (body != null)
{
Element rootElement = body.getDocumentElement();
NodeList childList = rootElement.getChildNodes();
m_propertyActions = new ArrayList<PropertyAction>();
for (int i = 0; i < childList.getLength(); i++)
{
Node currentNode = childList.item(i);
switch (currentNode.getNodeType())
{
case Node.TEXT_NODE:
break;
case Node.ELEMENT_NODE:
if (currentNode.getNodeName().endsWith(WebDAV.XML_SET) || currentNode.getNodeName().endsWith(WebDAV.XML_REMOVE))
{
NodeList propertiesList = currentNode.getChildNodes();
for (int j = 0; j < propertiesList.getLength(); j++)
{
Node propertiesNode = propertiesList.item(j);
switch (propertiesNode.getNodeType())
{
case Node.TEXT_NODE:
break;
case Node.ELEMENT_NODE:
if (propertiesNode.getNodeName().endsWith(WebDAV.XML_PROP))
{
NodeList propList = propertiesNode.getChildNodes();
for (int k = 0; k < propList.getLength(); k++)
{
Node propNode = propList.item(k);
switch (propNode.getNodeType())
{
case Node.TEXT_NODE:
break;
case Node.ELEMENT_NODE:
int action = currentNode.getNodeName().endsWith(WebDAV.XML_SET) ? PropertyAction.SET : PropertyAction.REMOVE;
m_propertyActions.add(new PropertyAction(action, createProperty(propNode)));
break;
}
}
}
break;
}
}
}
break;
}
}
}
}
示例15: testEntities001
import org.w3c.dom.Document; //导入方法依赖的package包/类
/**
* Equivalence class partitioning with state and input values orientation
* for public void setParameter(String name, Object value) throws
* DOMException, <br>
* <b>pre-conditions</b>: the doc contains one entity and one entity
* reference, <br>
* <b>name</b>: entities <br>
* <b>value</b>: true. <br>
* <b>Expected results</b>: the entity and the entity reference are left
* unchanged
*/
@Test
public void testEntities001() {
Document doc = null;
try {
doc = loadDocument(null, test1_xml);
} catch (Exception e) {
Assert.fail(e.getMessage());
}
DOMConfiguration config = doc.getDomConfig();
if (!config.canSetParameter("entities", Boolean.TRUE)) {
Assert.fail("setting 'entities' to true is not supported");
}
Element root = doc.getDocumentElement();
root.appendChild(doc.createEntityReference("x"));
config.setParameter("entities", Boolean.TRUE);
setHandler(doc);
doc.normalizeDocument();
Node child = root.getFirstChild();
if (child == null) {
Assert.fail("root has no child");
}
if (child.getNodeType() != Node.ENTITY_REFERENCE_NODE) {
Assert.fail("root's child is " + child + ", expected entity reference &x;");
}
if (doc.getDoctype() == null) {
Assert.fail("no doctype found");
}
if (doc.getDoctype().getEntities() == null) {
Assert.fail("no entitiy found");
}
if (doc.getDoctype().getEntities().getNamedItem("x") == null) {
Assert.fail("no entitiy with name 'x' found");
}
return; // Status.passed("OK");
}