本文整理了Java中org.w3c.dom.Element
类的一些代码示例,展示了Element
类的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Element
类的具体详情如下:
包路径:org.w3c.dom.Element
类名称:Element
[英]The Element
interface represents an element in an HTML or XML document. Elements may have attributes associated with them; since the Element
interface inherits from Node
, the generic Node
interface attribute attributes
may be used to retrieve the set of all attributes for an element. There are methods on the Element
interface to retrieve either an Attr
object by name or an attribute value by name. In XML, where an attribute value may contain entity references, an Attr
object should be retrieved to examine the possibly fairly complex sub-tree representing the attribute value. On the other hand, in HTML, where all attributes have simple string values, methods to directly access an attribute value can safely be used as a convenience.
Note: In DOM Level 2, the method normalize
is inherited from the Node
interface where it was moved.
See also the Document Object Model (DOM) Level 3 Core Specification.
[中]Element
接口表示HTML或XML文档中的元素。元素可能具有与其关联的属性;由于Element
接口继承自Node
,因此通用Node
接口属性attributes
可用于检索元素的所有属性集。Element
接口上有按名称检索Attr
对象或按名称检索属性值的方法。在XML中,属性值可能包含实体引用,应检索Attr
对象以检查表示属性值的可能相当复杂的子树。另一方面,在HTML中,所有属性都有简单的字符串值,可以安全地使用直接访问属性值的方法作为方便。
注意:在DOM级别2中,方法normalize
是从移动它的Node
接口继承的。
另见Document Object Model (DOM) Level 3 Core Specification。
代码示例来源:origin: apache/incubator-dubbo
private static void parseProperties(NodeList nodeList, RootBeanDefinition beanDefinition) {
if (nodeList != null && nodeList.getLength() > 0) {
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
if (node instanceof Element) {
if ("property".equals(node.getNodeName())
|| "property".equals(node.getLocalName())) {
String name = ((Element) node).getAttribute("name");
if (name != null && name.length() > 0) {
String value = ((Element) node).getAttribute("value");
String ref = ((Element) node).getAttribute("ref");
if (value != null && value.length() > 0) {
beanDefinition.getPropertyValues().addPropertyValue(name, value);
} else if (ref != null && ref.length() > 0) {
beanDefinition.getPropertyValues().addPropertyValue(name, new RuntimeBeanReference(ref));
} else {
throw new UnsupportedOperationException("Unsupported <property name=\"" + name + "\"> sub tag, Only supported <property name=\"" + name + "\" ref=\"...\" /> or <property name=\"" + name + "\" value=\"...\" />");
}
}
}
}
}
}
}
代码示例来源:origin: osmandapp/Osmand
protected static void copyAndReplaceElement(Element oldElement, Element newElement) {
while(oldElement.getChildNodes().getLength() > 0) {
newElement.appendChild(oldElement.getChildNodes().item(0));
}
NamedNodeMap attrs = oldElement.getAttributes();
for(int i = 0; i < attrs.getLength(); i++) {
Node ns = attrs.item(i);
newElement.setAttribute(ns.getNodeName(), ns.getNodeValue());
}
((Element)oldElement.getParentNode()).replaceChild(newElement, oldElement);
}
}
代码示例来源:origin: pentaho/pentaho-kettle
public String getSample( String strFunctionName, String strFunctionNameWithArgs ) {
String sRC = "// Sorry, no Script available for " + strFunctionNameWithArgs;
NodeList nl = dom.getElementsByTagName( "jsFunction" );
for ( int i = 0; i < nl.getLength(); i++ ) {
if ( nl.item( i ).getAttributes().getNamedItem( "name" ).getNodeValue().equals( strFunctionName ) ) {
Node elSample = ( (Element) nl.item( i ) ).getElementsByTagName( "sample" ).item( 0 );
if ( elSample.hasChildNodes() ) {
return ( elSample.getFirstChild().getNodeValue() );
}
}
}
return sRC;
}
代码示例来源:origin: spring-projects/spring-framework
@Override
protected String getBeanClassName(Element element) {
if (element.hasAttribute(WEAVER_CLASS_ATTRIBUTE)) {
return element.getAttribute(WEAVER_CLASS_ATTRIBUTE);
}
return DEFAULT_LOAD_TIME_WEAVER_CLASS_NAME;
}
代码示例来源:origin: spring-projects/spring-framework
@Nullable
String merge(Element element, ReaderContext readerCtx) {
String method = element.getAttribute(METHOD_ATTRIBUTE);
if (StringUtils.hasText(method)) {
return method.trim();
}
if (StringUtils.hasText(this.method)) {
return this.method;
}
readerCtx.error("No method specified for " + element.getNodeName(), element);
return null;
}
}
代码示例来源:origin: apache/hive
private Element appendElement(Element parent, String name, String text) {
Document document = parent.getOwnerDocument();
Element child = document.createElement(name);
parent.appendChild(child);
if (text != null) {
Text textNode = document.createTextNode(text);
child.appendChild(textNode);
}
return child;
}
代码示例来源:origin: wildfly/wildfly
protected void parseRules(InputStream input) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(false); // for now
DocumentBuilder builder=factory.newDocumentBuilder();
Document document=builder.parse(input);
Element root=document.getDocumentElement();
match(RULES, root.getNodeName(), true);
NodeList children=root.getChildNodes();
if(children == null || children.getLength() == 0)
return;
for(int i=0; i < children.getLength(); i++) {
Node node=children.item(i);
if(node.getNodeType() != Node.ELEMENT_NODE)
continue;
String element_name=node.getNodeName();
if(RULE.equals(element_name))
parseRule(node);
else
throw new Exception("expected <" + RULE + ">, but got " + "<" + element_name + ">");
}
}
代码示例来源:origin: alipay/sofa-boot
private static String getDependencyManagementPluginVersion() {
try (FileReader pomReader = new FileReader("pom.xml")) {
Document pom = DocumentBuilderFactory.newInstance().newDocumentBuilder()
.parse(new InputSource(pomReader));
NodeList dependencyElements = pom.getElementsByTagName("dependency");
for (int i = 0; i < dependencyElements.getLength(); i++) {
Element dependency = (Element) dependencyElements.item(i);
if (dependency.getElementsByTagName("artifactId").item(0).getTextContent()
.equals("dependency-management-plugin")) {
return dependency.getElementsByTagName("version").item(0).getTextContent();
}
}
throw new IllegalStateException("dependency management plugin version not found");
} catch (Exception ex) {
throw new IllegalStateException("Failed to find dependency management plugin version",
ex);
}
}
代码示例来源:origin: libgdx/libgdx
private void initData () throws ParserConfigurationException, IOException, SAXException {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = dbFactory.newDocumentBuilder();
Document doc = builder.parse(ExternalExtensionsDialog.class
.getResourceAsStream("/com/badlogic/gdx/setup/data/extensions.xml"));
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("extension");
for (int i = 0; i < nList.getLength(); i++) {
Node nNode = nList.item(i);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
String name = eElement.getElementsByTagName("name").item(0).getTextContent();
String description = eElement.getElementsByTagName("description").item(0).getTextContent();
String version = eElement.getElementsByTagName("version").item(0).getTextContent();
String compatibility = eElement.getElementsByTagName("compatibility").item(0).getTextContent();
String url = eElement.getElementsByTagName("website").item(0).getTextContent();
NodeList inheritsNode = eElement.getElementsByTagName("inherit");
gwtInherits = new String[inheritsNode.getLength()];
代码示例来源:origin: Tencent/tinker
BufferedInputStream input = null;
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
input = new BufferedInputStream(new FileInputStream(xmlConfigFile));
InputSource source = new InputSource(input);
factory.setNamespaceAware(false);
factory.setValidating(false);
DocumentBuilder builder = factory.newDocumentBuilder();
builder.setEntityResolver(new EntityResolver() {
@Override
public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
Document document = builder.parse(source);
NodeList issues = document.getElementsByTagName(TAG_ISSUE);
for (int i = 0, count = issues.getLength(); i < count; i++) {
Node node = issues.item(i);
String id = element.getAttribute(ATTR_ID);
if (id.length() == 0) {
System.err.println("Invalid config file: Missing required issue id attribute");
代码示例来源:origin: Tencent/tinker
private void readPackageConfigFromXml(Node node) throws IOException {
NodeList childNodes = node.getChildNodes();
if (childNodes.getLength() > 0) {
for (int j = 0, n = childNodes.getLength(); j < n; j++) {
Node child = childNodes.item(j);
if (child.getNodeType() == Node.ELEMENT_NODE) {
Element check = (Element) child;
String tagName = check.getTagName();
String value = check.getAttribute(ATTR_VALUE);
String name = check.getAttribute(ATTR_NAME);
if (tagName.equals(ATTR_CONFIG_FIELD)) {
mPackageFields.put(name, value);
} else {
System.err.println("unknown package config tag " + tagName);
}
}
}
}
}
代码示例来源:origin: stackoverflow.com
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
domFactory.setIgnoringComments(true);
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document doc = builder.parse(new File("XmlTest.xml"));
NodeList nodes = doc.getElementsByTagName("CustomerId");
Text a = doc.createTextNode("value");
Element p = doc.createElement("newNode");
p.appendChild(a);
nodes.item(0).getParentNode().insertBefore(p, nodes.item(0));
代码示例来源:origin: apache/nifi
private final String parseFingerprint(final String fingerprint) throws AuthorizationAccessException {
final byte[] fingerprintBytes = fingerprint.getBytes(StandardCharsets.UTF_8);
try (final ByteArrayInputStream in = new ByteArrayInputStream(fingerprintBytes)) {
final DocumentBuilder docBuilder = DOCUMENT_BUILDER_FACTORY.newDocumentBuilder();
final Document document = docBuilder.parse(in);
final Element rootElement = document.getDocumentElement();
final NodeList userGroupProviderList = rootElement.getElementsByTagName(USER_GROUP_PROVIDER_ELEMENT);
if (userGroupProviderList.getLength() != 1) {
throw new AuthorizationAccessException(String.format("Only one %s element is allowed: %s", USER_GROUP_PROVIDER_ELEMENT, fingerprint));
}
final Node userGroupProvider = userGroupProviderList.item(0);
return userGroupProvider.getTextContent();
} catch (SAXException | ParserConfigurationException | IOException e) {
throw new AuthorizationAccessException("Unable to parse fingerprint", e);
}
}
}
代码示例来源:origin: stanfordnlp/CoreNLP
public static List<Person> readXMLCharacterList(Document doc) {
List<Person> personList = new ArrayList<>();
NodeList characters = doc.getDocumentElement().getElementsByTagName("characters").item(0).getChildNodes();
for(int i = 0; i < characters.getLength(); i++)
{
Node child = characters.item(i);
if(child.getNodeName().equals("character")) {
String name = child.getAttributes().getNamedItem("name").getNodeValue();
char[] cName = name.toCharArray();
cName[0] = Character.toUpperCase(cName[0]);
name = new String(cName);
List<String> aliases = Arrays.asList(child.getAttributes().getNamedItem("aliases").getNodeValue().split(";"));
String gender = (child.getAttributes().getNamedItem("gender") == null) ? "" : child.getAttributes().getNamedItem("gender").getNodeValue();
personList.add(new Person(child.getAttributes().getNamedItem("name").getNodeValue(), gender, aliases));
}
}
return personList;
}
//write the character list to a file to work with the annotator
代码示例来源:origin: spring-projects/spring-framework
@Test
public void marshalDOMResult() throws Exception {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
documentBuilderFactory.setNamespaceAware(true);
DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();
Document result = builder.newDocument();
DOMResult domResult = new DOMResult(result);
marshaller.marshal(flights, domResult);
Document expected = builder.newDocument();
Element flightsElement = expected.createElementNS("http://samples.springframework.org/flight", "tns:flights");
Attr namespace = expected.createAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:tns");
namespace.setNodeValue("http://samples.springframework.org/flight");
flightsElement.setAttributeNode(namespace);
expected.appendChild(flightsElement);
Element flightElement = expected.createElementNS("http://samples.springframework.org/flight", "tns:flight");
flightsElement.appendChild(flightElement);
Element numberElement = expected.createElementNS("http://samples.springframework.org/flight", "tns:number");
flightElement.appendChild(numberElement);
Text text = expected.createTextNode("42");
numberElement.appendChild(text);
assertThat("Marshaller writes invalid DOMResult", result, isSimilarTo(expected));
}
代码示例来源:origin: osmandapp/Osmand
public static void combineAllApplyTags(Document document) {
NodeList nl = document.getElementsByTagName("apply");
while(nl.getLength() > 0) {
Element app = (Element) nl.item(0);
Element parent = (Element) app.getParentNode();
NamedNodeMap attrs = app.getAttributes();
for(int i = 0; i < attrs.getLength(); i++) {
Node ns = attrs.item(i);
parent.setAttribute(ns.getNodeName(), ns.getNodeValue());
}
while(app.getChildNodes().getLength() > 0) {
Node ni = app.getChildNodes().item(0);
app.getParentNode().insertBefore(ni, app);
}
app.getParentNode().removeChild(app);
}
}
代码示例来源:origin: spring-projects/spring-framework
public void parseMetaElements(Element ele, BeanMetadataAttributeAccessor attributeAccessor) {
NodeList nl = ele.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (isCandidateElement(node) && nodeNameEquals(node, META_ELEMENT)) {
Element metaElement = (Element) node;
String key = metaElement.getAttribute(KEY_ATTRIBUTE);
String value = metaElement.getAttribute(VALUE_ATTRIBUTE);
BeanMetadataAttribute attribute = new BeanMetadataAttribute(key, value);
attribute.setSource(extractSource(metaElement));
attributeAccessor.addMetadataAttribute(attribute);
}
}
}
代码示例来源:origin: spring-projects/spring-framework
@Test
public void marshalDOMResultToExistentDocument() throws Exception {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();
Document existent = builder.newDocument();
Element rootElement = existent.createElement("root");
Element flightsElement = existent.createElement("flights");
rootElement.appendChild(flightsElement);
existent.appendChild(rootElement);
// marshall into the existent document
DOMResult domResult = new DOMResult(flightsElement);
marshaller.marshal(flight, domResult);
Document expected = builder.newDocument();
Element eRootElement = expected.createElement("root");
Element eFlightsElement = expected.createElement("flights");
Element eFlightElement = expected.createElement("flight");
eRootElement.appendChild(eFlightsElement);
eFlightsElement.appendChild(eFlightElement);
expected.appendChild(eRootElement);
Element eNumberElement = expected.createElement("flightNumber");
eFlightElement.appendChild(eNumberElement);
Text text = expected.createTextNode("42");
eNumberElement.appendChild(text);
assertThat("Marshaller writes invalid DOMResult", existent, isSimilarTo(expected));
}
代码示例来源:origin: libgdx/libgdx
private void addToDependencyMapFromXML (Map<String, List<ExternalExtensionDependency>> dependencies, Element eElement, String platform) {
if (eElement.getElementsByTagName(platform).item(0) != null) {
Element project = (Element)eElement.getElementsByTagName(platform).item(0);
ArrayList<ExternalExtensionDependency> deps = new ArrayList<ExternalExtensionDependency>();
if (project.getTextContent().trim().equals("")) {
// No dependencies required
} else if (project.getTextContent().trim().equals("null")) {
// Not supported
deps = null;
} else {
NodeList nList = project.getElementsByTagName("dependency");
for (int i = 0; i < nList.getLength(); i++) {
Node nNode = nList.item(i);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element dependencyNode = (Element)nNode;
boolean external = Boolean.parseBoolean(dependencyNode.getAttribute("external"));
deps.add(new ExternalExtensionDependency(dependencyNode.getTextContent(), external));
}
}
}
dependencies.put(platform, deps);
}
}
代码示例来源:origin: ehcache/ehcache3
@Test
public void testPersistenceConfigXmlPersistencePathHasWhitespaces() throws Exception {
final URL resource = XmlConfigurationTest.class.getResource("/configs/persistence-config.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(new File(resource.toURI()));
Element persistence = (Element) doc.getElementsByTagName("ehcache:persistence").item(0);
String directoryValue = persistence.getAttribute("directory");
assertThat(directoryValue, containsString(" "));
assertThat(directoryValue, containsString("\r"));
assertThat(directoryValue, containsString("\n"));
assertThat(directoryValue, containsString("\t"));
}
内容来源于网络,如有侵权,请联系作者删除!