org.w3c.dom.Node类的使用及代码示例

x33g5p2x  于2022-01-24 转载在 其他  
字(17.5k)|赞(0)|评价(0)|浏览(448)

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

Node介绍

[英]The Node interface is the primary datatype for the entire Document Object Model. It represents a single node in the document tree. While all objects implementing the Node interface expose methods for dealing with children, not all objects implementing the Node interface may have children. For example, Text nodes may not have children, and adding children to such nodes results in a DOMException being raised.

The attributes nodeName, nodeValue and attributes are included as a mechanism to get at node information without casting down to the specific derived interface. In cases where there is no obvious mapping of these attributes for a specific nodeType (e.g., nodeValue for an Element or attributes for a Comment ), this returns null. Note that the specialized interfaces may contain additional and more convenient mechanisms to get and set the relevant information.

The values of nodeName, nodeValue, and attributes vary according to the node type as follows:
InterfacenodeNamenodeValueattributesAttrsame as Attr.namesame as Attr.value``null``CDATASection``"#cdata-section"same as CharacterData.data, the content of the CDATA Sectionnull``Comment``"#comment"same as CharacterData.data, the content of the commentnull``Document``"#document"``null``null``DocumentFragment``"#document-fragment"``null``null``DocumentTypesame as DocumentType.name``null``null``Elementsame as Element.tagName``null``NamedNodeMap``Entityentity namenull``null``EntityReferencename of entity referencednull``null``Notationnotation namenull``null``ProcessingInstructionsame as ProcessingInstruction.targetsame as ProcessingInstruction.data``null``Text``"#text"same as CharacterData.data, the content of the text nodenull

See also the Document Object Model (DOM) Level 3 Core Specification.
[中]Node接口是整个文档对象模型的主要数据类型。它表示文档树中的单个节点。虽然实现Node接口的所有对象都公开了处理子对象的方法,但并非所有实现Node接口的对象都可能有子对象。例如,Text节点可能没有子节点,向此类节点添加子节点会导致引发DOMException
属性nodeNamenodeValueattributes作为一种获取节点信息的机制包含在内,而无需向下转换到特定的派生接口。如果特定nodeType的这些属性没有明显的映射(例如ElementnodeValueCommentattributes,则返回null。请注意,专用接口可能包含用于获取和设置相关信息的附加和更方便的机制。
nodeNamenodeValueattributes的值根据节点类型的不同而不同,如下所示:
InterfaceNodeValueAttributesAttrAttr.name相同[$19$][$20$][$21$]"#cdata-section"CharacterData.data相同,CDATA部分的内容null[$25$]"#comment"CharacterData.data相同,该评论的内容的内容的内容的内容的评论的内容的内容的内容的内容的内容的内容的内容的内容的内容的内容的内容的内容的内容的内容的内容的回复[28美元,28美元,28,5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5null``ProcessingInstructionProcessingInstruction.target相同,与[$56$]null相同Text``"#text"CharacterData.data相同,文本节点的内容null
另见Document Object Model (DOM) Level 3 Core Specification

代码示例

代码示例来源:origin: stackoverflow.com

public static void main(String[] args) throws SAXException, IOException,
    ParserConfigurationException, TransformerException {

  DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
      .newInstance();
  DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
  Document document = docBuilder.parse(new File("document.xml"));

  NodeList nodeList = document.getElementsByTagName("*");
  for (int i = 0; i < nodeList.getLength(); i++) {
    Node node = nodeList.item(i);
    if (node.getNodeType() == Node.ELEMENT_NODE) {
      // do something with the current element
      System.out.println(node.getNodeName());
    }
  }
}

代码示例来源:origin: stackoverflow.com

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

public class Demo {

  public static void main(String[] args) throws Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document document = db.parse(new File("input.xml"));
    NodeList nodeList = document.getElementsByTagName("Item");
    for(int x=0,size= nodeList.getLength(); x<size; x++) {
      System.out.println(nodeList.item(x).getAttributes().getNamedItem("name").getNodeValue());
    }
  }
}

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

/** If the child node or attribute doesn't exist, it is created. Usage example: Node property =
 * getFirstChildByAttrValue(properties, "property", "name"); */
private static Node getFirstChildByNameAttrValue (Node node, String childName, String attr, String value) {
  NodeList childNodes = node.getChildNodes();
  for (int i = 0; i < childNodes.getLength(); i++) {
    if (childNodes.item(i).getNodeName().equals(childName)) {
      NamedNodeMap attributes = childNodes.item(i).getAttributes();
      Node attribute = attributes.getNamedItem(attr);
      if (attribute.getNodeValue().equals(value)) return childNodes.item(i);
    }
  }
  Node newNode = node.getOwnerDocument().createElement(childName);
  NamedNodeMap attributes = newNode.getAttributes();
  Attr nodeAttr = node.getOwnerDocument().createAttribute(attr);
  nodeAttr.setNodeValue(value);
  attributes.setNamedItem(nodeAttr);
  if (childNodes.item(0) != null) {
    return node.insertBefore(newNode, childNodes.item(0));
  } else {
    return node.appendChild(newNode);
  }
}

代码示例来源:origin: spring-projects/spring-framework

/**
 * Matches the given node's name and local name against the given desired name.
 */
private static boolean nodeNameMatch(Node node, String desiredName) {
  return (desiredName.equals(node.getNodeName()) || desiredName.equals(node.getLocalName()));
}

代码示例来源:origin: Tencent/tinker

private static String extractNameAttribute(Node node) {
  return node.getAttributes().getNamedItem("name").getNodeValue();
}

代码示例来源:origin: skylot/jadx

private void parse(Document doc) {
  NodeList nodeList = doc.getChildNodes();
  for (int count = 0; count < nodeList.getLength(); count++) {
    Node node = nodeList.item(count);
    if (node.getNodeType() == Node.ELEMENT_NODE
        && node.hasChildNodes()) {
      parseAttrList(node.getChildNodes());
    }
  }
}

代码示例来源: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: androidannotations/androidannotations

private AndroidManifest parse(File androidManifestFile, boolean libraryProject) throws AndroidManifestNotFoundException {
  DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
    doc = docBuilder.parse(androidManifestFile);
  } catch (Exception e) {
    LOGGER.error("Could not parse the AndroidManifest.xml file at path {}", androidManifestFile, e);
  Element documentElement = doc.getDocumentElement();
  documentElement.normalize();
  String applicationPackage = documentElement.getAttribute("package");
  boolean applicationDebuggableMode = false;
  if (applicationNodes.getLength() > 0) {
    Node applicationNode = applicationNodes.item(0);
    Node nameAttribute = applicationNode.getAttributes().getNamedItem("android:name");
        LOGGER.warn("The class application declared in the AndroidManifest.xml cannot be found in the compile path: [{}]", nameAttribute.getNodeValue());
    Node debuggableAttribute = applicationNode.getAttributes().getNamedItem("android:debuggable");
    if (debuggableAttribute != null) {
      applicationDebuggableMode = debuggableAttribute.getNodeValue().equalsIgnoreCase("true");

代码示例来源: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: stackoverflow.com

public static void main(String[] args) throws SAXException, IOException,
    ParserConfigurationException, TransformerException {

  DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
    .newInstance();
  DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
  Document document = docBuilder.parse(new File("document.xml"));
  doSomething(document.getDocumentElement());
}

public static void doSomething(Node node) {
  // do something with the current node instead of System.out
  System.out.println(node.getNodeName());

  NodeList nodeList = node.getChildNodes();
  for (int i = 0; i < nodeList.getLength(); i++) {
    Node currentNode = nodeList.item(i);
    if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
      //calls this method for all the children which is Element
      doSomething(currentNode);
    }
  }
}

代码示例来源: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();
      for (int j = 0; j < inheritsNode.getLength(); j++)
        gwtInherits[j] = inheritsNode.item(j).getTextContent();

代码示例来源:origin: Tencent/tinker

private void parse() throws ParserException {
  DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
  Document document;
  try {
    DocumentBuilder builder = builderFactory.newDocumentBuilder();
    builder.setEntityResolver(new EntityResolver() {
      @Override
      public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
    document = builder.parse(new ByteArrayInputStream(xml.getBytes("UTF-8")));
    Node manifestNode = document.getElementsByTagName("manifest").item(0);
    NodeList nodes = manifestNode.getChildNodes();
    for (int i = 0; i < nodes.getLength(); i++) {
      Node node = nodes.item(i);
      String nodeName = node.getNodeName();
      if (nodeName.equals("application")) {
        NodeList children = node.getChildNodes();
        for (int j = 0; j < children.getLength(); j++) {
          Node child = children.item(j);
          String childName = child.getNodeName();
          switch (childName) {
            case "service":
              break;
            case "meta-data":
              NamedNodeMap attributes = child.getAttributes();
              metaDatas.put(getAttribute(attributes, "android:name"), getAttribute(attributes, "android:value"));
              break;

代码示例来源:origin: languagetool-org/languagetool

private static Source mergeIntoSource(InputStream baseXmlStream, InputStream xmlStream) throws Exception {
 DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
 domFactory.setIgnoringComments(true);
 domFactory.setValidating(false);
 domFactory.setNamespaceAware(true);
 DocumentBuilder builder = domFactory.newDocumentBuilder();
 Document baseDoc = builder.parse(baseXmlStream);
 Document ruleDoc = builder.parse(xmlStream);
 // Shall this be more generic, i.e. reuse not just unification ???
 NodeList unificationNodes = baseDoc.getElementsByTagName("unification");
 Node ruleNode = ruleDoc.getElementsByTagName("rules").item(0);
 Node firstChildRuleNode = ruleNode.getChildNodes().item(1);
 for (int i = 0; i < unificationNodes.getLength(); i++) {
  Node unificationNode = ruleDoc.importNode(unificationNodes.item(i), true);
  ruleNode.insertBefore(unificationNode, firstChildRuleNode);
 }
 return new DOMSource(ruleDoc);
}

代码示例来源: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: marytts/marytts

@Test
public void testXMLParserSupportsNamespaces() throws Exception {
  DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  factory.setNamespaceAware(true);
  DocumentBuilder docBuilder = factory.newDocumentBuilder();
  Document document = docBuilder.parse(this.getClass().getResourceAsStream("test1.namespaces"));
  NodeList nl = document.getElementsByTagNameNS("http://www.w3.org/2001/10/synthesis", "*");
  assertNotNull(nl.item(0));
  assertTrue(nl.item(0).getNodeName().equals("ssml:emphasis"));
}

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

protected static List<Triple<Short,String,Boolean>> parse(InputStream stream) throws Exception {
  DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
  factory.setValidating(false); // for now
  DocumentBuilder builder=factory.newDocumentBuilder();
  Document document=builder.parse(stream);
  NodeList class_list=document.getElementsByTagName("class");
  List<Triple<Short,String,Boolean>> list=new LinkedList<>();
  for(int i=0; i < class_list.getLength(); i++) {
    if(class_list.item(i).getNodeType() == Node.ELEMENT_NODE) {
      list.add(parseClassData(class_list.item(i)));
    }
  }
  return list;
}

代码示例来源:origin: skylot/jadx

private void parseAttrList(NodeList nodeList) {
  for (int count = 0; count < nodeList.getLength(); count++) {
    Node tempNode = nodeList.item(count);
    if (tempNode.getNodeType() == Node.ELEMENT_NODE
        && tempNode.hasAttributes()
        && tempNode.hasChildNodes()) {
      String name = null;
      NamedNodeMap nodeMap = tempNode.getAttributes();
      for (int i = 0; i < nodeMap.getLength(); i++) {
        Node node = nodeMap.item(i);
        if (node.getNodeName().equals("name")) {
          name = node.getNodeValue();
          break;
        }
      }
      if (name != null && tempNode.getNodeName().equals("attr")) {
        parseValues(name, tempNode.getChildNodes());
      } else {
        parseAttrList(tempNode.getChildNodes());
      }
    }
  }
}

代码示例来源: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: 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: 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);
  }
}

相关文章