下面列出了怎么用org.w3c.dom.Element的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* This method creates an Element in a given namespace with a given localname.
* It uses the {@link ElementProxy#getDefaultPrefix} method to decide whether
* a particular prefix is bound to that namespace.
* <BR />
* This method was refactored out of the constructor.
*
* @param doc
* @param namespace
* @param localName
* @return The element created.
*/
public static Element createElementForFamily(Document doc, String namespace, String localName) {
Element result = null;
String prefix = ElementProxy.getDefaultPrefix(namespace);
if (namespace == null) {
result = doc.createElementNS(null, localName);
} else {
if ((prefix == null) || (prefix.length() == 0)) {
result = doc.createElementNS(namespace, localName);
result.setAttributeNS(Constants.NamespaceSpecNS, "xmlns", namespace);
} else {
result = doc.createElementNS(namespace, prefix + ":" + localName);
result.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:" + prefix, namespace);
}
}
return result;
}
public boolean appendHTML(String tag, Element child, boolean multiStar, boolean[] srai, boolean isTemplate, StringWriter writer, Network network) {
writer.write("<");
writer.write(tag);
NamedNodeMap attributes = child.getAttributes();
for (int index = 0; index < attributes.getLength(); index++) {
Node attribute = attributes.item(index);
writer.write(" ");
writer.write(attribute.getNodeName());
writer.write("=\\\"");
writer.write(attribute.getNodeValue());
writer.write("\\\"");
}
if (!child.hasChildNodes()) {
writer.write("/>");
} else {
writer.write(">");
if (appendNestedText((Element)child, multiStar, srai, writer, network)) {
isTemplate = true;
}
writer.write("</");
writer.write(tag);
writer.write(">");
}
return isTemplate;
}
protected T buildModel(Element root) {
B builder = builder();
builder
.withName(root.getAttribute("name"))
.withNamespace(root.getAttribute("namespace"))
.withVersion(root.getAttribute("version"));
NodeList nodes = root.getElementsByTagNameNS(schemaURI, "description");
if (nodes.getLength() > 0)
{
Element description = (Element)nodes.item(0);
builder.withDescription(readDescription(description));
}
else {
logger.warn("No description was given for the capability {}", root.getAttribute("name"));
}
populateDefinitionSpecificData(builder, root);
builder.withMethods(buildMethods(root.getElementsByTagNameNS(schemaURI, "method")));
builder.withEvents(buildEvents(root.getElementsByTagNameNS(schemaURI, "event")));
return builder.build();
}
/**
* toXML.
* {@inheritDoc}
* @param doc - The document.
* @return The element.
*/
public Element toXml(Document doc) {
Element propfind = DomUtil.createElement(doc, XML_PROPFIND, NAMESPACE);
if (propertyNames.isEmpty()) {
// allprop
Element allprop =
DomUtil.createElement(doc, XML_ALLPROP, NAMESPACE);
propfind.appendChild(allprop);
}
else {
for (DavPropertyName propname: propertyNames) {
Element name =
DomUtil.createElement(doc, propname.getName(),
propname.getNamespace());
Element prop = DomUtil.createElement(doc, XML_PROP, NAMESPACE);
prop.appendChild(name);
propfind.appendChild(prop);
}
}
return propfind;
}
public static void addBundleRequirement ( final Set<String> context, final Element requires, final ArtifactInformation a )
{
final String id = a.getMetaData ().get ( new MetaKey ( "osgi", "name" ) );
if ( id == null )
{
return;
}
final String version = a.getMetaData ().get ( new MetaKey ( "osgi", "version" ) );
final String key = String.format ( "%s.feature.group-%s", id, version );
if ( !context.add ( key ) )
{
return;
}
final Element p = requires.getOwnerDocument ().createElement ( "required" );
requires.appendChild ( p );
p.setAttribute ( "namespace", "org.eclipse.equinox.p2.iu" );
p.setAttribute ( "name", id );
p.setAttribute ( "range", String.format ( "[%1$s,%1$s]", version ) );
}
/**
* Create a {@link RootBeanDefinition} for the advisor described in the supplied. Does <strong>not</strong>
* parse any associated '{@code pointcut}' or '{@code pointcut-ref}' attributes.
*/
private AbstractBeanDefinition createAdvisorBeanDefinition(Element advisorElement, ParserContext parserContext) {
RootBeanDefinition advisorDefinition = new RootBeanDefinition(DefaultBeanFactoryPointcutAdvisor.class);
advisorDefinition.setSource(parserContext.extractSource(advisorElement));
String adviceRef = advisorElement.getAttribute(ADVICE_REF);
if (!StringUtils.hasText(adviceRef)) {
parserContext.getReaderContext().error(
"'advice-ref' attribute contains empty value.", advisorElement, this.parseState.snapshot());
}
else {
advisorDefinition.getPropertyValues().add(
ADVICE_BEAN_NAME, new RuntimeBeanNameReference(adviceRef));
}
if (advisorElement.hasAttribute(ORDER_PROPERTY)) {
advisorDefinition.getPropertyValues().add(
ORDER_PROPERTY, advisorElement.getAttribute(ORDER_PROPERTY));
}
return advisorDefinition;
}
private void collectValues(final String revocationValuesPath, RevocationOrigin revocationOrigin) {
if (revocationValuesPath == null) {
return;
}
final NodeList revocationValuesNodeList = DomUtils.getNodeList(signatureElement, revocationValuesPath);
for (int i = 0; i < revocationValuesNodeList.getLength(); i++) {
final Element revocationValuesElement = (Element) revocationValuesNodeList.item(i);
final NodeList crlValueNodes = DomUtils.getNodeList(revocationValuesElement, xadesPaths.getCurrentCRLValuesChildren());
for (int ii = 0; ii < crlValueNodes.getLength(); ii++) {
try {
final Element crlValueEl = (Element) crlValueNodes.item(ii);
if (crlValueEl != null) {
CRLBinary crlBinary = CRLUtils.buildCRLBinary(Utils.fromBase64(crlValueEl.getTextContent()));
addBinary(crlBinary, revocationOrigin);
}
} catch (Exception e) {
LOG.warn("Unable to build CRLBinary from an obtained element with origin {}", revocationOrigin);
}
}
}
}
/**
* Creates a BPEL assign activity that reads the property values from a NodeInstance Property response and sets the
* given variables
*
* @param assignName the name of the assign activity
* @param nodeInstancePropertyResponseVarName the name of the variable holding the property data
* @param propElement2BpelVarNameMap a Map from DOM Elements (representing Node Properties) to BPEL
* variable names
* @return a String containing a BPEL assign activity
* @throws IOException is thrown when reading internal files fail
*/
public String createAssignFromInstancePropertyToBPELVariableAsString(final String assignName,
final String nodeInstancePropertyResponseVarName,
final Map<Element, String> propElement2BpelVarNameMap) throws IOException {
final String template = ResourceAccess.readResourceAsString(getClass().getClassLoader().getResource("core-bpel/BpelCopyFromPropertyVarToNodeInstanceProperty.xml"));
String assignString =
"<bpel:assign name=\"" + assignName + "\" xmlns:bpel=\"" + BPELPlan.bpelNamespace + "\" >";
// <!-- $PropertyVarName, $NodeInstancePropertyRequestVarName,
// $NodeInstancePropertyLocalName, $NodeInstancePropertyNamespace -->
for (final Element propElement : propElement2BpelVarNameMap.keySet()) {
String copyString = template.replace("$PropertyVarName", propElement2BpelVarNameMap.get(propElement));
copyString = copyString.replace("$NodeInstancePropertyRequestVarName", nodeInstancePropertyResponseVarName);
copyString = copyString.replace("$NodeInstancePropertyLocalName", propElement.getLocalName());
copyString = copyString.replace("$NodeInstancePropertyNamespace", propElement.getNamespaceURI());
assignString += copyString;
}
assignString += "</bpel:assign>";
BPELProcessFragments.LOG.debug("Generated following assign string:");
BPELProcessFragments.LOG.debug(assignString);
return assignString;
}
private List<PomPluginElement> getPlugins(Element parent) {
Element buildElement = getFirstChildElement(parent, "build");
Element pluginsElement = getFirstChildElement(buildElement, PLUGINS);
if (pluginsElement == null) {
return Collections.emptyList();
}
NodeList children = pluginsElement.getChildNodes();
List<PomPluginElement> plugins = new LinkedList<>();
for (int i = 0; i < children.getLength(); i++) {
Node node = children.item(i);
if (node instanceof Element && PLUGIN.equals(node.getNodeName())) {
plugins.add(new PomPluginElement((Element) node));
}
}
return plugins;
}
public static List<Element> getElements(final Element e, final String name)
{
List<Element> retValue = new ArrayList<>();
for (Node object = e.getFirstChild(); object != null; object = object.getNextSibling())
{
if (object instanceof Element)
{
final Element en = (Element) object;
if (name == null || name.equals(en.getTagName()))
{
retValue.add(en);
}
}
}
return retValue;
}
public static byte[] encrypt(Document doc, Crypto crypto, String detailId) throws TechnicalConnectorException, TransformerException, UnsupportedEncodingException {
NodeList nodes = doc.getElementsByTagNameNS("urn:be:cin:encrypted", "EncryptedKnownContent");
String content = toStringOmittingXmlDeclaration(nodes);
SignatureBuilder builder = SignatureBuilderFactory.getSignatureBuilder(AdvancedElectronicSignatureEnumeration.XAdES);
Map<String, Object> options = new HashMap();
List<String> tranforms = new ArrayList();
tranforms.add("http://www.w3.org/2000/09/xmldsig#base64");
tranforms.add("http://www.w3.org/2001/10/xml-exc-c14n#");
options.put("transformerList", tranforms);
options.put("baseURI", detailId);
options.put("encapsulate", true);
options.put("encapsulate-transformer", new EncapsulationTransformer() {
public Node transform(Node signature) {
Element result = signature.getOwnerDocument().createElementNS("urn:be:cin:encrypted", "Xades");
result.setTextContent(Base64.encodeBase64String(ConnectorXmlUtils.toByteArray(signature)));
return result;
}
});
byte[] encryptedKnowContent = builder.sign(Session.getInstance().getSession().getEncryptionCredential(), content.getBytes("UTF-8"), options);
return seal(crypto, encryptedKnowContent);
}
/**
* Test the compilation of a invalid state attribute strings, except
* locations
*
* @throws SAXException
* Exception thrown by parser
* @throws IOException
* Exception thrown by parser
* @throws ParserConfigurationException
* Exception thrown by parser
*/
@Test
public void testInvalidStateAttributeCompilation() throws SAXException, IOException, ParserConfigurationException {
String[] invalidStrings = { "<stateAttribute type=\"constant\" />",
"<stateAttribute type=\"eventField\" />",
"<stateAttribute type=\"query\" />",
"<stateAttribute type=\"query\" ><stateAttribute type=\"constant\" /></stateAttribute>",
"<stateAttribute type=\"location\" value=\"undefined\" />"
};
for (String invalidString : invalidStrings) {
Element xmlElement = TmfXmlTestUtils.getXmlElement(TmfXmlStrings.STATE_ATTRIBUTE, invalidString);
assertNotNull(xmlElement);
assertNull(invalidString, TmfXmlStateValueCu.compileAttribute(ANALYSIS_DATA, xmlElement));
}
}
/**
* Import Map from the specified input stream, which is assumed to contain a map
* document as per the prefs DTD. This is used as the internal (undocumented)
* format for FileSystemPrefs. The key-value pairs specified in the XML document
* will be put into the specified Map. (If this Map is empty, it will contain
* exactly the key-value pairs int the XML-document when this method returns.)
*
* @throws IOException
* if reading from the specified output stream results in an
* <tt>IOException</tt>.
* @throws InvalidPreferencesFormatException
* Data on input stream does not constitute a valid XML document
* with the mandated document type.
*/
static void importMap(InputStream is, Map m) throws IOException, InvalidPreferencesFormatException {
try {
Document doc = loadPrefsDoc(is);
Element xmlMap = doc.getDocumentElement();
// check version
String mapVersion = xmlMap.getAttribute("MAP_XML_VERSION");
if (mapVersion.compareTo(MAP_XML_VERSION) > 0)
throw new InvalidPreferencesFormatException("Preferences map file format version " + mapVersion
+ " is not supported. This java installation can read" + " versions " + MAP_XML_VERSION
+ " or older. You may need" + " to install a newer version of JDK.");
NodeList entries = xmlMap.getChildNodes();
for (int i = 0, numEntries = entries.getLength(); i < numEntries; i++) {
Element entry = (Element) entries.item(i);
m.put(entry.getAttribute("key"), entry.getAttribute("value"));
}
} catch (SAXException e) {
throw new InvalidPreferencesFormatException(e);
}
}
@SuppressWarnings("SameParameterValue")
private static void addPropertyReferenceArray(
RootBeanDefinition definition, Element element, String elementTypeName, String propertyName, boolean required) {
String[] refArray = Strings.split(element.getAttribute(propertyName), ',');
List<RuntimeBeanReference> refBeanList = Lists.newArrayListWithCapacity(refArray.length);
for (String ref : refArray) {
ref = ref.trim();
if (required) {
checkAttribute(propertyName, ref);
}
if (!Strings.isNullOrEmpty(ref)) {
refBeanList.add(new RuntimeBeanReference(ref));
}
}
if (!refBeanList.isEmpty()) {
ManagedArray managedArray = new ManagedArray(elementTypeName, refBeanList.size());
managedArray.addAll(refBeanList);
definition.getPropertyValues().addPropertyValue(propertyName, managedArray);
}
}
/**
* Set an attribute on the named target element. The target element must exist
* and be a child of the project-element.
*
* @param el
* The element owning the target element to be updated.
* @param name
* The name of the target-element to set an attribute for.
* @param attrName
* The name of the attribute to set.
* @param attrValue
* The new attribute value.
*/
private void setTargetAttr(final Element el, final String name, final String attrName, final String attrValue) {
final NodeList propertyNL = el.getElementsByTagName("target");
boolean found = false;
for (int i = 0; i<propertyNL.getLength(); i++) {
final Element target = (Element) propertyNL.item(i);
if (name.equals(target.getAttribute("name"))) {
log("Setting <target name=\"" +name +"\" attrName =\"" +attrValue +"\" ...>.", Project.MSG_DEBUG);
target.setAttribute(attrName, attrValue);
found = true;
break;
}
}
if (!found) {
throw new BuildException("No <property name=\"" +name +"\" ...> in XML document " +el);
}
}
/**
* Encrypts a <code>NodeList</code> (the contents of an
* <code>Element</code>) and replaces its parent <code>Element</code>'s
* content with this the resulting <code>EncryptedType</code> within the
* context <code>Document</code>, that is, the <code>Document</code>
* specified when one calls
* {@link #getInstance(String) getInstance}.
*
* @param element the <code>NodeList</code> to encrypt.
* @return the context <code>Document</code> with the encrypted
* <code>NodeList</code> having replaced the content of the source
* <code>Element</code>.
* @throws Exception
*/
private Document encryptElementContent(Element element) throws /* XMLEncryption */Exception {
if (log.isLoggable(java.util.logging.Level.FINE)) {
log.log(java.util.logging.Level.FINE, "Encrypting element content...");
}
if (null == element) {
log.log(java.util.logging.Level.SEVERE, "Element unexpectedly null...");
}
if (cipherMode != ENCRYPT_MODE && log.isLoggable(java.util.logging.Level.FINE)) {
log.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in ENCRYPT_MODE...");
}
if (algorithm == null) {
throw new XMLEncryptionException("XMLCipher instance without transformation specified");
}
encryptData(contextDocument, element, true);
Element encryptedElement = factory.toElement(ed);
removeContent(element);
element.appendChild(encryptedElement);
return contextDocument;
}
public void marshal(Node parent, String dsPrefix, DOMCryptoContext context)
throws MarshalException
{
Document ownerDoc = DOMUtils.getOwnerDocument(parent);
Element propsElem = DOMUtils.createElement(ownerDoc,
"SignatureProperties",
XMLSignature.XMLNS,
dsPrefix);
// set attributes
DOMUtils.setAttributeID(propsElem, "Id", id);
// create and append any properties
for (SignatureProperty property : properties) {
((DOMSignatureProperty)property).marshal(propsElem, dsPrefix,
context);
}
parent.appendChild(propsElem);
}
/**
* Returns the <code>i<code>th <code>ds:Object</code> child of the signature
* or null if no such <code>ds:Object</code> element exists.
*
* @param i
* @return the <code>i<code>th <code>ds:Object</code> child of the signature
* or null if no such <code>ds:Object</code> element exists.
*/
public ObjectContainer getObjectItem(int i) {
Element objElem =
XMLUtils.selectDsNode(
this.constructionElement.getFirstChild(), Constants._TAG_OBJECT, i
);
try {
return new ObjectContainer(objElem, this.baseURI);
} catch (XMLSecurityException ex) {
return null;
}
}
/**
* First previous start tag at higher level is my parent.
* Skip all end-tag start-tag pairs at the same level.
* @return SyntaxNode or <code>null</code>
*/
public Node getParentNode() {
SyntaxNode prev = findPrevious();
do {
while ( prev != null ) {
if (prev instanceof StartTag) {
return (Element) prev;
} else if (prev instanceof EndTag) { // traverse end-start tag pairs
prev = ((EndTag)prev).getStartTag();
if (prev == null) break;
prev = prev.findPrevious();
} else {
prev = prev.findPrevious();
}
}
if (prev == null) break;
} while ( (prev instanceof SyntaxNode) == false );
if (prev != null) {
return (Node) prev;
} else {
return getOwnerDocument(); //??? return a DocumentFragment with some kids? or null
}
}
private Element servicesXml() {
return parse(
"<http>",
" <filtering>",
" <filter id='outer' />",
" <request-chain id='myChain'>",
" <filter id='inner' />",
" </request-chain>",
" </filtering>",
"</http>");
}
/** Gets the fist child of the given name, or null. */
public static Element getFirstChildElement( Element parent, String nsUri, String localPart ) {
NodeList children = parent.getChildNodes();
for( int i=0; i<children.getLength(); i++ ) {
Node item = children.item(i);
if(!(item instanceof Element )) continue;
if(nsUri.equals(item.getNamespaceURI())
&& localPart.equals(item.getLocalName()) )
return (Element)item;
}
return null;
}
public List<String> getSterrotypes() {
NodeList nl = getPeer().getElementsByTagName(Stereotype.STEREOTYPE);
List<String> result = new ArrayList<String>( nl.getLength());
if (nl != null) {
for (int i=0; i<nl.getLength(); i++) {
if (WebBeansElements.STEREOTYPE.getQName(model).equals(
getQName(nl.item(i))))
{
result.add(getText((Element) nl.item(i)));
}
}
}
return result;
}
/**
* Parse an EscapeCraft tag for the given <code>Entity</code>.
*
* @param escCraftTag
* @param entity
*/
private void parseEscapeCraft(Element escCraftTag, Entity entity){
if (!(entity instanceof SmallCraft || entity instanceof Jumpship)) {
warning.append("Found an EscapeCraft tag but Entity is not a " +
"Crewed Spacecraft!\n");
return;
}
try {
String id = escCraftTag.getAttribute(ID);
((Aero) entity).addEscapeCraft(id);
} catch (Exception e) {
warning.append("Invalid external entity id in EscapeCraft tag.\n");
}
}
public DOMMessage(SOAPVersion ver, MessageHeaders headers, Element payload, AttachmentSet attachments) {
super(ver);
this.headers = headers;
this.payload = payload;
this.attachmentSet = attachments;
assert payload!=null;
}
public static SAMLToken createSAMLToken(Properties configuration, String samlTokenString) throws Exception{
final String systemKeystoreFile = configuration.getProperty(SYSTEM_KEYSTORE_FILE);
final String systemKeystorePassword = configuration.getProperty(SYSTEM_KEYSTORE_PASSWORD);
loadEHealthConfig(configuration);
final Element sessionElement = SAML10Converter.toElement(samlTokenString);
final Credential credential = new KeyStoreCredential(systemKeystoreFile, systemKeystorePassword, AUTHENTICATION_ALIAS, systemKeystorePassword);
return new SAMLHolderOfKeyToken(sessionElement, credential);
}
private static Map getOrigin(Element element)
{
String mode = "";
String namc = "";
Properties info = new Properties();
NamedNodeMap atts = element.getAttributes();
for (int i = 0; i < atts.getLength(); i ++)
{
Node attr = atts.item(i);
String name = attr.getNodeName();
String value = attr.getNodeValue();
if ("jndi".equals(name))
{
mode = value;
}
if ("name".equals(name))
{
namc = value;
}
else
{
info.setProperty(name, value);
}
}
// 2016/9/4 增加 source,origin 的 param 节点, 附加设置可使用 param
getProperties(element, info);
Map origin = new HashMap();
origin.put("jndi", mode);
origin.put("name", namc);
origin.put("info", info);
return origin;
}
public DOMMessage(SOAPVersion ver, MessageHeaders headers, Element payload, AttachmentSet attachments) {
super(ver);
this.headers = headers;
this.payload = payload;
this.attachmentSet = attachments;
assert payload!=null;
}
protected Element writeActionResponseElement(Document d,
Element bodyElement,
ActionResponseMessage message,
ActionInvocation actionInvocation) {
log.fine("Writing action response element: " + actionInvocation.getAction().getName());
Element actionResponseElement = d.createElementNS(
message.getActionNamespace(),
"u:" + actionInvocation.getAction().getName() + "Response"
);
bodyElement.appendChild(actionResponseElement);
return actionResponseElement;
}
private static Document createLibraryDefinition1(
final @NonNull LibraryImplementation library,
final @NonNull LibraryTypeProvider libraryTypeProvider) {
final Document doc = XMLUtil.createDocument(LIBRARY, null,
LIBRARY_DEF_1,
LIBRARY_DTD_1);
final Element libraryE = doc.getDocumentElement();
libraryE.setAttribute(VERSION, VER_1); // NOI18N
libraryE.appendChild(doc.createElement(NAME)).appendChild(doc.createTextNode(library.getName())); // NOI18N
libraryE.appendChild(doc.createElement(TYPE)).appendChild(doc.createTextNode(library.getType())); // NOI18N
String description = library.getDescription();
if (description != null && description.length() > 0) {
libraryE.appendChild(doc.createElement(DESCRIPTION)).appendChild(doc.createTextNode(description)); // NOI18N
}
String localizingBundle = library.getLocalizingBundle();
if (localizingBundle != null && localizingBundle.length() > 0) {
libraryE.appendChild(doc.createElement(BUNDLE)).appendChild(doc.createTextNode(localizingBundle)); // NOI18N
}
String displayname = LibrariesSupport.getDisplayName(library);
if (displayname != null) {
libraryE.appendChild(doc.createElement(DISPLAY_NAME)).appendChild(doc.createTextNode(displayname)); // NOI18N
}
for (String vtype : libraryTypeProvider.getSupportedVolumeTypes()) {
Element volumeE = (Element) libraryE.appendChild(doc.createElement(VOLUME)); // NOI18N
volumeE.appendChild(doc.createElement(TYPE)).appendChild(doc.createTextNode(vtype)); // NOI18N
List<URL> volume = library.getContent(vtype);
if (volume != null) {
//If null -> broken library, repair it.
for (URL url : volume) {
volumeE.appendChild(doc.createElement(RESOURCE)).appendChild(doc.createTextNode(url.toString())); // NOI18N
}
}
}
return doc;
}
/**
* Given a configuration element, extract the params map.
*
* @param confElem the configuration element
* @return the params map or an empty map if one can't be found
*/
public static Map<String, String> getConfigurationParameters(Element confElem) {
Map<String, String> paramsMap = new HashMap<String, String>();
Node paramsNode = confElem.getElementsByTagName("params").item(0);
if (paramsNode != null) {
NodeList paramsList = paramsNode.getChildNodes();
for (int j = 0; j < paramsList.getLength(); j++) {
Node paramNode = paramsList.item(j);
if (paramNode != null && !paramsMap.containsKey(paramNode.getNodeName())) {
paramsMap.put(paramNode.getNodeName(), paramNode.getTextContent());
}
}
}
return paramsMap;
}