codememo

Java: org.w3c.dom의 모든 요소에 대해 반복하기에 가장 효율적인 방법입니다.문서?

tipmemo 2023. 11. 4. 10:49
반응형

Java: org.w3c.dom의 모든 요소에 대해 반복하기에 가장 효율적인 방법입니다.문서?

자바의 모든 DOM 요소를 통해 반복하는 가장 효율적인 방법은 무엇입니까?

전류의 모든 DOM 요소에 대해 이와 유사합니다.org.w3c.dom.Document?

for(Node childNode = node.getFirstChild(); childNode!=null;){
    Node nextChild = childNode.getNextSibling();
    // Do something with childNode, including move or delete...
    childNode = nextChild;
}

기본적으로 모든 요소를 반복하는 두 가지 방법이 있습니다.

1. 재귀를 사용하는 방법(가장 일반적인 방법):

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);
        }
    }
}

2. 를 사용하여 재귀 방지getElementsByTagName()메소드 위드*매개 변수:

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());
        }
    }
}

저는 이 방법이 둘 다 효율적이라고 생각합니다.

for (int i = 0; i < nodeList.getLength(); i++)

로 바꾸다

for (int i = 0, len = nodeList.getLength(); i < len; i++)

더 효율적으로 하기 위해서.

자바나 답변의 두 번째 방법은 더 평탄하고 예측 가능한 기억 모델을 사용하는 경향이 있기 때문에 가장 좋을 수 있습니다.

저도 최근에 이 문제를 우연히 발견했습니다.이것이 제 해결책입니다.재귀를 피하고 싶어서 잠시 루프를 사용했습니다.

목록의 임의의 위치에 있는 추가 및 제거 때문에, 저는 다음과 같이 진행했습니다.LinkedList실행.

/* traverses tree starting with given node */
  private static List<Node> traverse(Node n)
  {
    return traverse(Arrays.asList(n));
  }

  /* traverses tree starting with given nodes */
  private static List<Node> traverse(List<Node> nodes)
  {
    List<Node> open = new LinkedList<Node>(nodes);
    List<Node> visited = new LinkedList<Node>();

    ListIterator<Node> it = open.listIterator();
    while (it.hasNext() || it.hasPrevious())
    {
      Node unvisited;
      if (it.hasNext())
        unvisited = it.next();
      else
        unvisited = it.previous();

      it.remove();

      List<Node> children = getChildren(unvisited);
      for (Node child : children)
        it.add(child);

      visited.add(unvisited);
    }

    return visited;
  }

  private static List<Node> getChildren(Node n)
  {
    List<Node> children = asList(n.getChildNodes());
    Iterator<Node> it = children.iterator();
    while (it.hasNext())
      if (it.next().getNodeType() != Node.ELEMENT_NODE)
        it.remove();
    return children;
  }

  private static List<Node> asList(NodeList nodes)
  {
    List<Node> list = new ArrayList<Node>(nodes.getLength());
    for (int i = 0, l = nodes.getLength(); i < l; i++)
      list.add(nodes.item(i));
    return list;
  }

언급URL : https://stackoverflow.com/questions/5386991/java-most-efficient-method-to-iterate-over-all-elements-in-a-org-w3c-dom-docume

반응형