XTreeCursor로 탐색
XTreeCursor 인터페이스를 사용하여 데이터를 볼 수 있습니다.
이 태스크 정보
XPath 또는 XQuery 표현식이나 XSLT 스타일시트를 평가한 결과 노드를 포함하는 시퀀스를 가정합니다. 해당 노드에 XPath 또는 XQuery 표현식을 적용하여 노드의 컨텐츠에 대한 간편하게 액세스할 수 있습니다. 그러나 XML API를 통해 직접 노드와 연관된 트리 구조를 탐색하도록 선택할 수 있습니다.
프로시저
예
다음 예제에서는 XML 데이터를 포함하는 트리를 탐색하기 위해 XTreeCursor 인터페이스에서 메소드를 사용하는 방법을 보여줍니다.
/* Contents of library.xml
<library>
<book title='Ulysses'><author><first>James</first><last>Joyce</last></author></book>
<book title='Ada'><author><first>Vladimir</first><last>Nabokov</last></author></book>
</library>
*/
XItemFactory factory = XFactory.newInstance().getItemFactory();
XItemView item = factory.item(new StreamSource("library.xml"));
// 'tree' is initially positioned at the same node as
// 'item' - that is, the document node of the input
XTreeCursor tree = item.getTreeCursor();
// Position tree cursor to "library" element
tree.toFirstChild();
// Position tree cursor to white-space text node
tree.toFirstChild();
// Position to first "book" element
tree.toNextSibling();
// Position to white-space text node
tree.toNextSibling();
// Position to second "book" element
tree.toNextSibling();
// Create a second instance of XTreeCursor that is initially
// positioned at the same node as 'tree' - that is, the
// second "book" element
XTreeCursor secondBook = tree.getTreeCursor();
// Position 'tree' to "library" element
tree.toParent();
// Position 'secondBook' to "title" attribute
secondBook.toFirstAttribute();
다음 예제에서는 깊이 우선 방식으로 트리에서 모든 노드를 탐색합니다.
XItemFactory factory = XFactory.newInstance().getItemFactory();
XItemView item = factory.item(new StreamSource("library.xml"));
XTreeCursor tree = item.getTreeCursor();
boolean hasMoreNodes = true;
do {
// Process current node
if (tree.toFirstAttribute()) {
do {
// Process attributes
} while (tree.toNextAttribute());
tree.toParent();
}
if (tree.toFirstNamespace()) {
do {
// Process namespaces
} while (tree.toFirstNamespace());
tree.toParent();
}
boolean foundNext = false;
// If the current node has a child, visit it next
// If there's no child, go to the next sibling
if (tree.toFirstChild() || tree.toNextSibling()) {
foundNext = true;
// If there's no child and no sibling, find an
// ancestor's sibling instead.
} else {
do {
hasMoreNodes = tree.toParent();
if (hasMoreNodes) {
foundNext = tree.toNextSibling();
}
} while (hasMoreNodes && !foundNext);
}
} while (hasMoreNodes);