在XSLT中输出错误?

时间:2011-12-06 12:28:20

标签: java xslt xpath

以下是XML文件 -

<Seminars>
  <Seminar>
    <Venue P="ABC" dt="20111223"/>
    <Subject name="Finance">
      <Topic main="Bonds"/>
      <Topic main="Stocks" sub="Technical Analysis"/>
    </Subject>       
  </Seminar>    
  <Seminar>
    <Venue P="ABC" dt="20111225"/>
    <Subject name="Yoga">
      <Topic main="Benefits"/>
    </Subject>
    <Subject name="Meditation">
      <Topic main="Benefits"/>
    </Subject>
  </Seminar>
  <Seminar>
    <Venue P="PQR" dt="20111220"/>       
    <Subject name="IT">
       <Topic main="Java" sub="Swing"/>
       <Topic main="Java" sub="NIO"/>
    </Subject>       
  </Seminar>
  <Seminar>
    <Venue P="ABC" dt="20111224"/>
    <Subject name="Medical">
       <Topic main="Plastic Surgery"/>
       <Topic main="Mal-nutrition"/>
    </Subject>
    <Subject name="IT">
       <Topic main="Java" sub="Collections"/>
       <Topic main="Web Technologies"/>
    </Subject>      
  </Seminar>
  <Seminar>     
    <Venue P="XYZ" dt="20111226"/>
    <Subject name="IT">
      <Topic main="DotNET - I"/>
      <Topic main="DotNET - II"/>
      <Topic main="XML" sub="Security"/>
    </Subject>       
  </Seminar>
  <Seminar>
     <Venue P="XYZ" dt="20111227"/>
     <Subject name="IT">
        <Topic main="Oracle"/>
        <Topic main="Oracle" sub="JDeveloper"/>
     </Subject>       
  </Seminar>
</Seminars>

以下是Java程序 -

import org.w3c.dom.*;
import javax.xml.xpath.*;
import javax.xml.parsers.*;
import java.io.IOException;
import org.xml.sax.SAXException;

public class Seminar
{
   public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException 
   {
      DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
      domFactory.setNamespaceAware(true); 
      DocumentBuilder builder = domFactory.newDocumentBuilder();
      Document doc = builder.parse("seminar.xml");
      XPath xpath = XPathFactory.newInstance().newXPath();

      String qry = "//Seminars/Seminar[contains(Subject/@name,'Medical')]/Subject/Topic/@main";
      XPathExpression expr = xpath.compile(qry);
      Object result = expr.evaluate(doc, XPathConstants.NODESET);
      NodeList nodes = (NodeList) result;

      for (int i = 0; i < nodes.getLength(); i++) 
      {
           System.out.println(nodes.item(i).getNodeValue());
      }
   }
}

使用上面的程序我期待输出为 -

Plastic Surgery
Mal-nutrition

但我也获得了下一个Subject代码的输出,该代码的属性值为 IT ...... ???

查询中缺少什么...?

2 个答案:

答案 0 :(得分:3)

您的查询应该是

  String qry = "//Seminars/Seminar/Subject[contains(@name,'Medical')]/Topic/@main";

您要求在SeminarSubject中包含@nameTopics的所有主题。新查询要求@name中包含“Medical”的Subject中的所有{{1}}。微妙但重要的区别!

答案 1 :(得分:2)

您的XPath将为所有至少有一个名为 Medical 的主题的研讨会提供所有主题/主题[@main]。

你可能想要

String qry = "//Seminars/Seminar/Subject[contains(@name,'Medical')]/Topic/@main";

String qry = "//Seminars/Seminar/Subject[@name='Medical']/Topic/@main";