有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

xml Java Xpath查询

如何使用Java Xpath将第二个“c”标记d和f的值取为2

<a>
    <b>
        <c type="lol">
            <d>1</d>
            <f>2</f>
        </c>
        <c type="lol">
            <d>2</d>
            <f>2</f>
        </c>
            <c type="h">
            <d>v</d>
            <f>d</f>
        </c>
    </b>
</a>

 { 
    DocumentBuilderFactory dBFactory = DocumentBuilderFactory.newInstance();
  DocumentBuilder dB = dBFactory.newDocumentBuilder();
  Document doc = dB.parse(url);     
  System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
  XPathFactory factory = XPathFactory.newInstance();
  XPath xpath = factory.newXPath();
  XPathExpression expr=null;
  String text= null;
  expr= xpath.compile("//a/b/c[@type='lol']/d/text()");// this gets the first value
  text = (String) expr.evaluate(doc, XPathConstants.STRING);
     } 

如何使用Java Xpath将第二个“c”标记d和f的值取为2


共 (1) 个答案

  1. # 1 楼答案

    使用:

    //a/b/c[@type='lol'][2]/d/text()