使用 XTreeCursor 导航

您可以使用 XTreeCursor 接口来查看数据。

关于此任务

假定对 XPath 或 XQuery 表达式或 XSLT 样式表求值生成的序列包含节点。您将会发现通过向这些节点应用更多 XPath 或 XQuery 表达式,更易于访问这些节点的内容。但是,还可以选择通过树结构进行导航,此树结构直接通过 XML API 与节点关联。

过程

示例

以下示例说明您可以如何使用 XTreeCursor 接口上的方法,通过包含 XML 数据的树进行导航。

/* 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);

指示主题类型的图标 任务主题



时间戳记图标 最近一次更新时间: last_date
http://www14.software.ibm.com/webapp/wsbroker/redirect?version=cord&product=was-nd-mp&topic=txml_nav_xtree
文件名:txml_nav_xtree.html