Xpath - 具有以子字符串开头的相同名称的多个标记

时间:2015-12-13 01:41:38

标签: xpath

我有这个XML文件,我需要获取一本书的名称和作者,其中至少有一位作者的名字以“E”开头。

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE library SYSTEM  "knihy.dtd">
<library>
<book isbn="0470114878">
    <author hlavni="hlavni">David Hunter</author>
    <author>Jeff Rafter</author>
    <author>Joe Fawcett</author>
    <author>Eric van der Vlist</author>
    <author>Danny Ayers</author>
    <name>Beginning XML</name>
    <publisher>Wrox</publisher>
</book>
<book isbn="0596004206">
    <author>Erik Ray</author>
    <name>Learning XML</name>
    <publisher>O'Reilly</publisher>
</book>
<book isbn="0764547593">
    <author>Kay Ethier</author>
    <author>Alan Houser</author>
    <name>XML Weekend Crash Course</name>
    <year>2001</year>
</book>
<book isbn="1590596765">
    <author>Sas Jacobs</author>
    <name>Beginning XML with DOM and Ajax</name>
    <publisher>Apress</publisher>
    <year>2006</year>
</book>
</library>

我试过这种方法

for $book in /library/book[starts-with(author, "E")]
return $book

但它在invokeTransform中返回XPathException:不允许多个项目的序列作为starts-with()的第一个参数(“David Hunter”,“Jeff Rafter”,......)。那我怎么检查这个序列呢?

1 个答案:

答案 0 :(得分:3)

如错误消息所示,在谓词中使用starts-with()表示单个author元素,而不是将所有author子元素传递给starts-with()立刻发挥作用:

for $book in /library/book[author[starts-with(., "E")]]
return $book

<强> xpathtester demo

以上内容将返回book中至少有一个author的名称以"E"开头的所有<book isbn="0470114878"> <author hlavni="hlavni">David Hunter</author> <author>Jeff Rafter</author> <author>Joe Fawcett</author> <author>Eric van der Vlist</author> <author>Danny Ayers</author> <name>Beginning XML</name> <publisher>Wrox</publisher> </book> <book isbn="0596004206"> <author>Erik Ray</author> <name>Learning XML</name> <publisher>O'Reilly</publisher> </book>

输出

public class JavaFXApplication4 extends Application {

@Override
public void start(Stage stage) {
   Button jb = new Button("Click");
   jb.setOnMouseClicked(new EventHandler() {
        @Override
           public void handle(Event event) {
               makeAnotherStage(stage);
           }
       });

       GridPane gp = new GridPane();
       gp.getChildren().add(jb);
       Scene s = new Scene(gp);

       stage.setScene(s);
       stage.show();

    }

    private void makeAnotherStage(Stage st){
        Stage s = new Stage();

        GridPane gp = new GridPane();
        Label l = new Label("Second Stage");
        gp.getChildren().add(l);
        Scene sc = new Scene(gp);

        s.initOwner(st);                        <------- initOwner
        s.initModality(Modality.WINDOW_MODAL);  <------- Modality property

        s.setScene(sc);
        s.requestFocus();
        s.show();
    }
}
相关问题