下面列出了怎么用org.w3c.dom.traversal.NodeIterator的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* @serialData Serialized fields. Convert Maps to Hashtables and Lists
* to Vectors for backward compatibility.
*/
private void writeObject(ObjectOutputStream out) throws IOException {
// Convert Maps to Hashtables, Lists to Vectors
Vector<NodeIterator> it = (iterators == null)? null : new Vector<>(iterators);
Vector<Range> r = (ranges == null)? null : new Vector<>(ranges);
Hashtable<NodeImpl, Vector<LEntry>> el = null;
if (eventListeners != null) {
el = new Hashtable<>();
for (Map.Entry<NodeImpl, List<LEntry>> e : eventListeners.entrySet()) {
el.put(e.getKey(), new Vector<>(e.getValue()));
}
}
// Write serialized fields
ObjectOutputStream.PutField pf = out.putFields();
pf.put("iterators", it);
pf.put("ranges", r);
pf.put("eventListeners", el);
pf.put("mutationEvents", mutationEvents);
out.writeFields();
}
@SuppressWarnings("unchecked")
private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException {
// We have to read serialized fields first.
ObjectInputStream.GetField gf = in.readFields();
Vector<NodeIterator> it = (Vector<NodeIterator>)gf.get("iterators", null);
Vector<Range> r = (Vector<Range>)gf.get("ranges", null);
Hashtable<NodeImpl, Vector<LEntry>> el =
(Hashtable<NodeImpl, Vector<LEntry>>)gf.get("eventListeners", null);
mutationEvents = gf.get("mutationEvents", false);
//convert Hashtables back to HashMaps and Vectors to Lists
if (it != null) iterators = new ArrayList<>(it);
if (r != null) ranges = new ArrayList<>(r);
if (el != null) {
eventListeners = new HashMap<>();
for (Map.Entry<NodeImpl, Vector<LEntry>> e : el.entrySet()) {
eventListeners.put(e.getKey(), new ArrayList<>(e.getValue()));
}
}
}
/**
* Create and return a NodeIterator. The NodeIterator is
* added to a list of NodeIterators so that it can be
* removed to free up the DOM Nodes it references.
*
* @param root The root of the iterator.
* @param whatToShow The whatToShow mask.
* @param filter The NodeFilter installed. Null means no filter.
* @param entityReferenceExpansion true to expand the contents of
* EntityReference nodes
* @since WD-DOM-Level-2-19990923
*/
public NodeIterator createNodeIterator(Node root,
int whatToShow,
NodeFilter filter,
boolean entityReferenceExpansion)
{
if (root == null) {
String msg = DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NOT_SUPPORTED_ERR", null);
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, msg);
}
NodeIterator iterator = new NodeIteratorImpl(this,
root,
whatToShow,
filter,
entityReferenceExpansion);
if (iterators == null) {
iterators = new ArrayList<>();
}
iterators.add(iterator);
return iterator;
}
/**
* @serialData Serialized fields. Convert Maps to Hashtables and Lists
* to Vectors for backward compatibility.
*/
private void writeObject(ObjectOutputStream out) throws IOException {
// Convert Maps to Hashtables, Lists to Vectors
Vector<NodeIterator> it = (iterators == null)? null : new Vector<>(iterators);
Vector<Range> r = (ranges == null)? null : new Vector<>(ranges);
Hashtable<NodeImpl, Vector<LEntry>> el = null;
if (eventListeners != null) {
el = new Hashtable<>();
for (Map.Entry<NodeImpl, List<LEntry>> e : eventListeners.entrySet()) {
el.put(e.getKey(), new Vector<>(e.getValue()));
}
}
// Write serialized fields
ObjectOutputStream.PutField pf = out.putFields();
pf.put("iterators", it);
pf.put("ranges", r);
pf.put("eventListeners", el);
pf.put("mutationEvents", mutationEvents);
out.writeFields();
}
/**
* @serialData Serialized fields. Convert Maps to Hashtables and Lists
* to Vectors for backward compatibility.
*/
private void writeObject(ObjectOutputStream out) throws IOException {
// Convert Maps to Hashtables, Lists to Vectors
Vector<NodeIterator> it = (iterators == null)? null : new Vector<>(iterators);
Vector<Range> r = (ranges == null)? null : new Vector<>(ranges);
Hashtable<NodeImpl, Vector<LEntry>> el = null;
if (eventListeners != null) {
el = new Hashtable<>();
for (Map.Entry<NodeImpl, List<LEntry>> e : eventListeners.entrySet()) {
el.put(e.getKey(), new Vector<>(e.getValue()));
}
}
// Write serialized fields
ObjectOutputStream.PutField pf = out.putFields();
pf.put("iterators", it);
pf.put("ranges", r);
pf.put("eventListeners", el);
pf.put("mutationEvents", mutationEvents);
out.writeFields();
}
/**
* Copy NodeList members into this nodelist, adding in
* document order. Null references are not added.
*
* @param iterator NodeIterator which yields the nodes to be added.
* @throws RuntimeException thrown if this NodeSet is not of
* a mutable type.
*/
public void addNodes(NodeIterator iterator)
{
if (!m_mutable)
throw new RuntimeException(XSLMessages.createXPATHMessage(XPATHErrorResources.ER_NODESET_NOT_MUTABLE, null)); //"This NodeSet is not mutable!");
if (null != iterator) // defensive to fix a bug that Sanjiva reported.
{
Node obj;
while (null != (obj = iterator.nextNode()))
{
addElement(obj);
}
}
// checkDups();
}
/**
* @throws Exception if the test fails
*/
@Test
public void nextNode() throws Exception {
final String html = "<html><head><script>\n"
+ "function test() {\n"
+ "}\n"
+ "</script></head>\n"
+ "<body onload='test()'>\n"
+ " <form name='f1'>\n"
+ " <input>\n"
+ " <INPUT>\n"
+ " </form>\n"
+ "</body></html>";
final WebDriver driver = loadPageWithAlerts2(html);
if (driver instanceof HtmlUnitDriver) {
final WebWindow webWindow = getWebWindowOf((HtmlUnitDriver) driver);
final HtmlPage page = (HtmlPage) webWindow.getEnclosedPage();
final NodeIterator iterator = page.createNodeIterator(page.getDocumentElement(), NodeFilter.SHOW_ALL, null,
true);
assertThat(iterator.nextNode(), instanceOf(HtmlHtml.class));
}
}
/**
* Copy NodeList members into this nodelist, adding in
* document order. Null references are not added.
*
* @param iterator NodeIterator which yields the nodes to be added.
* @throws RuntimeException thrown if this NodeSet is not of
* a mutable type.
*/
public void addNodes(NodeIterator iterator)
{
if (!m_mutable)
throw new RuntimeException(XSLMessages.createXPATHMessage(XPATHErrorResources.ER_NODESET_NOT_MUTABLE, null)); //"This NodeSet is not mutable!");
if (null != iterator) // defensive to fix a bug that Sanjiva reported.
{
Node obj;
while (null != (obj = iterator.nextNode()))
{
addElement(obj);
}
}
// checkDups();
}
/**
* Copy NodeList members into this nodelist, adding in
* document order. Null references are not added.
*
* @param iterator NodeIterator which yields the nodes to be added.
* @throws RuntimeException thrown if this NodeSet is not of
* a mutable type.
*/
public void addNodes(NodeIterator iterator)
{
if (!m_mutable)
throw new RuntimeException(XSLMessages.createXPATHMessage(XPATHErrorResources.ER_NODESET_NOT_MUTABLE, null)); //"This NodeSet is not mutable!");
if (null != iterator) // defensive to fix a bug that Sanjiva reported.
{
Node obj;
while (null != (obj = iterator.nextNode()))
{
addElement(obj);
}
}
// checkDups();
}
@SuppressWarnings("unchecked")
private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException {
// We have to read serialized fields first.
ObjectInputStream.GetField gf = in.readFields();
Vector<NodeIterator> it = (Vector<NodeIterator>)gf.get("iterators", null);
Vector<Range> r = (Vector<Range>)gf.get("ranges", null);
Hashtable<NodeImpl, Vector<LEntry>> el =
(Hashtable<NodeImpl, Vector<LEntry>>)gf.get("eventListeners", null);
mutationEvents = gf.get("mutationEvents", false);
//convert Hashtables back to HashMaps and Vectors to Lists
if (it != null) iterators = new ArrayList<>(it);
if (r != null) ranges = new ArrayList<>(r);
if (el != null) {
eventListeners = new HashMap<>();
for (Map.Entry<NodeImpl, Vector<LEntry>> e : el.entrySet()) {
eventListeners.put(e.getKey(), new ArrayList<>(e.getValue()));
}
}
}
/**
* Create and return a NodeIterator. The NodeIterator is
* added to a list of NodeIterators so that it can be
* removed to free up the DOM Nodes it references.
*
* @param root The root of the iterator.
* @param whatToShow The whatToShow mask.
* @param filter The NodeFilter installed. Null means no filter.
* @param entityReferenceExpansion true to expand the contents of
* EntityReference nodes
* @since WD-DOM-Level-2-19990923
*/
public NodeIterator createNodeIterator(Node root,
int whatToShow,
NodeFilter filter,
boolean entityReferenceExpansion)
{
if (root == null) {
String msg = DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NOT_SUPPORTED_ERR", null);
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, msg);
}
NodeIterator iterator = new NodeIteratorImpl(this,
root,
whatToShow,
filter,
entityReferenceExpansion);
if (iterators == null) {
iterators = new ArrayList<>();
}
iterators.add(iterator);
return iterator;
}
/**
* Use an XPath string to select a nodelist.
* XPath namespace prefixes are resolved from the namespaceNode.
*
* @param contextNode The node to start searching from.
* @param str A valid XPath string.
* @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces.
* @return A NodeIterator, should never be null.
*
* @throws TransformerException
*/
public NodeIterator selectNodeIterator(
Node contextNode, String str, Node namespaceNode)
throws TransformerException
{
// Execute the XPath, and have it return the result
XObject list = eval(contextNode, str, namespaceNode);
// Have the XObject return its result as a NodeSetDTM.
return list.nodeset();
}
/**
* Create a NodeSetDTM, and copy the members of the
* given DTMIterator into it.
*
* @param iterator Iterator which yields Nodes to be made members of the new set.
*/
public NodeSetDTM(NodeIterator iterator, XPathContext xctxt)
{
super();
Node node;
m_manager = xctxt.getDTMManager();
while (null != (node = iterator.nextNode()))
{
int handle = xctxt.getDTMHandleFromNode(node);
addNodeInDocOrder(handle, xctxt);
}
}
/** This is not called by the developer client. The
* developer client uses the detach() function on the
* NodeIterator itself. <p>
*
* This function is called from the NodeIterator#detach().
*/
void removeNodeIterator(NodeIterator nodeIterator) {
if (nodeIterator == null) return;
if (iterators == null) return;
iterators.remove(nodeIterator);
}
public XNodeSetForDOM(NodeIterator nodeIter, XPathContext xctxt)
{
m_dtmMgr = xctxt.getDTMManager();
m_origObj = nodeIter;
// JKESS 20020514: Longer-term solution is to force
// folks to request length through an accessor, so we can defer this
// retrieval... but that requires an API change.
// m_obj = new com.sun.org.apache.xpath.internal.NodeSetDTM(nodeIter, xctxt);
com.sun.org.apache.xpath.internal.NodeSetDTM nsdtm=new com.sun.org.apache.xpath.internal.NodeSetDTM(nodeIter, xctxt);
m_last=nsdtm.getLength();
setObject(nsdtm);
}
/**
* Cast result object to a nodelist. Always issues an error.
*
* @return null
*
* @throws javax.xml.transform.TransformerException
*/
public NodeIterator nodeset() throws javax.xml.transform.TransformerException
{
error(XPATHErrorResources.ER_CANT_CONVERT_TO_NODELIST,
new Object[]{ getTypeString() }); //"Can not convert "+getTypeString()+" to a NodeList!");
return null;
}
/**
* Use an XPath string to select a single node.
* XPath namespace prefixes are resolved from the namespaceNode.
*
* @param contextNode The node to start searching from.
* @param str A valid XPath string.
* @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces.
* @return The first node found that matches the XPath, or null.
*
* @throws TransformerException
*/
public static Node selectSingleNode(
Node contextNode, String str, Node namespaceNode)
throws TransformerException
{
// Have the XObject return its result as a NodeSetDTM.
NodeIterator nl = selectNodeIterator(contextNode, str, namespaceNode);
// Return the first node, or null
return nl.nextNode();
}
/**
* Cast result object to a nodelist. Always issues an error.
*
* @return null
*
* @throws javax.xml.transform.TransformerException
*/
public NodeIterator nodeset() throws javax.xml.transform.TransformerException
{
error(XPATHErrorResources.ER_CANT_CONVERT_TO_NODELIST,
new Object[]{ getTypeString() }); //"Can not convert "+getTypeString()+" to a NodeList!");
return null;
}
/**
* Create a NodeSetDTM, and copy the members of the
* given DTMIterator into it.
*
* @param iterator Iterator which yields Nodes to be made members of the new set.
*/
public NodeSetDTM(NodeIterator iterator, XPathContext xctxt)
{
super();
Node node;
m_manager = xctxt.getDTMManager();
while (null != (node = iterator.nextNode()))
{
int handle = xctxt.getDTMHandleFromNode(node);
addNodeInDocOrder(handle, xctxt);
}
}
/**
* Create a NodeSet, and copy the members of the
* given NodeSet into it.
*
* @param nodelist Set of Nodes to be made members of the new set.
*/
public NodeSet(NodeSet nodelist)
{
this(32);
addNodes((NodeIterator) nodelist);
}
/** This is not called by the developer client. The
* developer client uses the detach() function on the
* NodeIterator itself. <p>
*
* This function is called from the NodeIterator#detach().
*/
void removeNodeIterator(NodeIterator nodeIterator) {
if (nodeIterator == null) return;
if (iterators == null) return;
iterators.remove(nodeIterator);
}
/**
* Copy NodeList members into this nodelist, adding in
* document order. If a node is null, don't add it.
*
* @param iterator NodeIterator which yields the nodes to be added.
* @param support The XPath runtime context.
* @throws RuntimeException thrown if this NodeSet is not of
* a mutable type.
*/
public void addNodesInDocOrder(NodeIterator iterator, XPathContext support)
{
if (!m_mutable)
throw new RuntimeException(XSLMessages.createXPATHMessage(XPATHErrorResources.ER_NODESET_NOT_MUTABLE, null)); //"This NodeSet is not mutable!");
Node node;
while (null != (node = iterator.nextNode()))
{
addNodeInDocOrder(node, support);
}
}
private Object getResultAsType( XObject resultObject, QName returnType )
throws javax.xml.transform.TransformerException {
// XPathConstants.STRING
if ( returnType.equals( XPathConstants.STRING ) ) {
return resultObject.str();
}
// XPathConstants.NUMBER
if ( returnType.equals( XPathConstants.NUMBER ) ) {
return new Double ( resultObject.num());
}
// XPathConstants.BOOLEAN
if ( returnType.equals( XPathConstants.BOOLEAN ) ) {
return new Boolean( resultObject.bool());
}
// XPathConstants.NODESET ---ORdered, UNOrdered???
if ( returnType.equals( XPathConstants.NODESET ) ) {
return resultObject.nodelist();
}
// XPathConstants.NODE
if ( returnType.equals( XPathConstants.NODE ) ) {
NodeIterator ni = resultObject.nodeset();
//Return the first node, or null
return ni.nextNode();
}
String fmsg = XSLMessages.createXPATHMessage(
XPATHErrorResources.ER_UNSUPPORTED_RETURN_TYPE,
new Object[] { returnType.toString()});
throw new IllegalArgumentException( fmsg );
}
private Object getResultAsType( XObject resultObject, QName returnType )
throws javax.xml.transform.TransformerException {
// XPathConstants.STRING
if ( returnType.equals( XPathConstants.STRING ) ) {
return resultObject.str();
}
// XPathConstants.NUMBER
if ( returnType.equals( XPathConstants.NUMBER ) ) {
return new Double ( resultObject.num());
}
// XPathConstants.BOOLEAN
if ( returnType.equals( XPathConstants.BOOLEAN ) ) {
return new Boolean( resultObject.bool());
}
// XPathConstants.NODESET ---ORdered, UNOrdered???
if ( returnType.equals( XPathConstants.NODESET ) ) {
return resultObject.nodelist();
}
// XPathConstants.NODE
if ( returnType.equals( XPathConstants.NODE ) ) {
NodeIterator ni = resultObject.nodeset();
//Return the first node, or null
return ni.nextNode();
}
// If isSupported check is already done then the execution path
// shouldn't come here. Being defensive
String fmsg = XSLMessages.createXPATHMessage(
XPATHErrorResources.ER_UNSUPPORTED_RETURN_TYPE,
new Object[] { returnType.toString()});
throw new IllegalArgumentException ( fmsg );
}
/**
* The value of this single node result, which may be <code>null</code>.
* @exception XPathException
* TYPE_ERR: raised if <code>resultType</code> is not
* <code>ANY_UNORDERED_NODE_TYPE</code> or
* <code>FIRST_ORDERED_NODE_TYPE</code>.
*
* @see org.w3c.dom.xpath.XPathResult#getSingleNodeValue()
*/
public Node getSingleNodeValue() throws XPathException {
if ((m_resultType != ANY_UNORDERED_NODE_TYPE) &&
(m_resultType != FIRST_ORDERED_NODE_TYPE)) {
String fmsg = XPATHMessages.createXPATHMessage(XPATHErrorResources.ER_CANT_CONVERT_TO_SINGLENODE, new Object[] {m_xpath.getPatternString(), getTypeString(m_resultType)});
throw new XPathException(XPathException.TYPE_ERR,fmsg);
// "The XPathResult of XPath expression {0} has an XPathResultType of {1} which cannot be converted to a single node.
// This method applies only to types ANY_UNORDERED_NODE_TYPE and FIRST_ORDERED_NODE_TYPE."
}
NodeIterator result = null;
try {
result = m_resultObj.nodeset();
} catch (TransformerException te) {
throw new XPathException(XPathException.TYPE_ERR,te.getMessage());
}
if (null == result) return null;
Node node = result.nextNode();
// Wrap "namespace node" in an XPathNamespace
if (isNamespaceNode(node)) {
return new XPathNamespaceImpl(node);
} else {
return node;
}
}
/**
* Use an XPath string to select a nodelist.
* XPath namespace prefixes are resolved from the namespaceNode.
*
* @param contextNode The node to start searching from.
* @param str A valid XPath string.
* @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces.
* @return A NodeIterator, should never be null.
*
* @throws TransformerException
*/
public NodeIterator selectNodeIterator(
Node contextNode, String str, Node namespaceNode)
throws TransformerException
{
// Execute the XPath, and have it return the result
XObject list = eval(contextNode, str, namespaceNode);
// Have the XObject return its result as a NodeSetDTM.
return list.nodeset();
}
/**
* Create a NodeSet, and copy the members of the
* given NodeIterator into it.
*
* @param ni Iterator which yields Nodes to be made members of the new set.
*/
public NodeSet(NodeIterator ni)
{
this(32);
addNodes(ni);
}
/**
* Use an XPath string to select a nodelist.
* XPath namespace prefixes are resolved from the namespaceNode.
*
* @param contextNode The node to start searching from.
* @param str A valid XPath string.
* @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces.
* @return A NodeIterator, should never be null.
*
* @throws TransformerException
*/
public NodeIterator selectNodeIterator(
Node contextNode, String str, Node namespaceNode)
throws TransformerException
{
// Execute the XPath, and have it return the result
XObject list = eval(contextNode, str, namespaceNode);
// Have the XObject return its result as a NodeSetDTM.
return list.nodeset();
}
public XNodeSetForDOM(NodeIterator nodeIter, XPathContext xctxt)
{
m_dtmMgr = xctxt.getDTMManager();
m_origObj = nodeIter;
// JKESS 20020514: Longer-term solution is to force
// folks to request length through an accessor, so we can defer this
// retrieval... but that requires an API change.
// m_obj = new com.sun.org.apache.xpath.internal.NodeSetDTM(nodeIter, xctxt);
com.sun.org.apache.xpath.internal.NodeSetDTM nsdtm=new com.sun.org.apache.xpath.internal.NodeSetDTM(nodeIter, xctxt);
m_last=nsdtm.getLength();
setObject(nsdtm);
}
/**
* Use an XPath string to select a single node.
* XPath namespace prefixes are resolved from the namespaceNode.
*
* @param contextNode The node to start searching from.
* @param str A valid XPath string.
* @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces.
* @return The first node found that matches the XPath, or null.
*
* @throws TransformerException
*/
public static Node selectSingleNode(
Node contextNode, String str, Node namespaceNode)
throws TransformerException
{
// Have the XObject return its result as a NodeSetDTM.
NodeIterator nl = selectNodeIterator(contextNode, str, namespaceNode);
// Return the first node, or null
return nl.nextNode();
}