gpt4 book ai didi

java - 在 XSLT 中得到错误的输出?

转载 作者:行者123 更新时间:2023-11-29 08:10:28 26 4
gpt4 key购买 nike

下面是 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 ...???

我在查询中遗漏了什么...?

最佳答案

你的查询应该是

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

您要求的是 Seminar 中的所有主题,其中包含 @name 中带有“Medical”的 Subject。新查询要求在@name 中包含“Medical”的Subject 中的所有Topics。细微但重要的区别!

关于java - 在 XSLT 中得到错误的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8399884/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com