4

我有一个从 JavaFX 2.2 WebEngine 获得的 Document 对象。在下面的代码中,即使加载的文档有小写的 html 标签,getDocumentElement().getNodeName() 也会以大写形式返回它。结果,XPath 查询无法定位节点(因为它需要小写的 html 标记)。在这种特殊情况下,我可以强制 getNodeName() 的输出为小写,但一般来说,如果文档有混合大小写标签,如何处理呢?

public class XPath3 extends Application {

WebView view;
WebEngine engine;

@Override
public void start(Stage primaryStage) {

    view = new WebView();
    engine = view.getEngine();

    engine.getLoadWorker().stateProperty().addListener(
            new ChangeListener<Worker.State>() {
        @Override
        public void changed(ObservableValue<? extends Worker.State> ov, Worker.State t, Worker.State t1) {
            if (t1 == Worker.State.SUCCEEDED) {
                Document doc = engine.getDocument();
                XPath xPath = XPathFactory.newInstance().newXPath();
                xPath.setNamespaceContext(new NamespaceContext() {
                    @Override
                    public String getNamespaceURI(String pfx) {
                        if ("ns1".equals(pfx)) {
                            return "http://www.w3.org/1999/xhtml";
                        }
                        return XMLConstants.NULL_NS_URI;
                    }

                    @Override
                    public String getPrefix(String string) {
                        return null;
                    }

                    @Override
                    public Iterator getPrefixes(String string) {
                        return null;
                    }
                });
                NodeList nl = null;
                String path = "/ns1:" + doc.getDocumentElement().getNodeName();
                //path = "/ns1:html";
                System.out.println(path);
                try {
                    nl = (NodeList) xPath.compile(path).evaluate(doc, XPathConstants.NODESET);
                } catch (XPathExpressionException ex) {
                    System.exit(-11);
                }
                System.out.println("XPath: " + path + "    Count: " + nl.getLength());
                System.exit(-1);
            }
        }
    });

    Platform.runLater(new Runnable() {
        @Override
        public void run() {
            engine.loadContent("<html><body> hello! </body></html>");
        }
    });
}

/**
 * The main() method is ignored in correctly deployed JavaFX application.
 * main() serves only as fallback in case the application can not be
 * launched through deployment artifacts, e.g., in IDEs with limited FX
 * support. NetBeans ignores main().
 *
 * @param args the command line arguments
 */
public static void main(String[] args) {
    launch(args);
}

}

4

0 回答 0