Ниже приведен 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 ... ???
Чего мне не хватает в запросе ...