我正在学习使用Java的XML和XSLT。我已经使用这些技术很久以前用ASP 3和Javascript创建了一些应用程序。现在我正在尝试使用Xpath记住一些技巧,并了解如何在Java中进行此操作。如何做Xpath的结果成为我的输出结果?
我曾经在过去制作一个Xpath来从XML获取一些元素并将其转换为我的HTML输出。我一直试图在java中做同样的事情,但我认为我有点失落。
我已经在这里寻找其他人的帖子,但通常这些样本只是获取节点的值并显示在一个循环中。我想获得一段XML并将其转换为输出HTML。
我有这个简单的样品波纹管,它工作正常。
Source source = new StreamSource("catalog.xml");
Source xsl = new StreamSource("catalog.xsl");
//Result result = new StreamResult(System.out);
Result result = new StreamResult("output.html");
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer(xsl);
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.transform(source, result);
我正在使用javax.xml。 。我看到了几个使用javax.xml.xpath的例子。。我也测试了一些Xpath的例子。
但到目前为止,我还没有意识到如何从XML获取代码片段代码,并将其转换为我的output.html文件。
我的XML:
<catalog>
<cd active="1">
<title>Empire Burlesque</title>
<artist>Bob Dylan</artist>
<country>USA</country>
<company>Columbia</company>
<price>10.90</price>
<year>1985</year>
</cd>
<cd active="1">
<title>Hide your heart</title>
<artist>Bonnie Tyler</artist>
<country>UK</country>
<company>CBS Records</company>
<price>9.90</price>
<year>1988</year>
</cd>
<cd active="0">
<title>Greatest Hits</title>
<artist>Dolly Parton</artist>
<country>USA</country>
<company>RCA</company>
<price>9.90</price>
<year>1982</year>
</cd>
</catalog>
例如,如果我想在我output.html改造只是这个XPath波纹管:
XPathExpression expr = xpath.compile("//catalog/cd[active='0']");
如何做到这一点在我的Java?
- 我知道我可以在我的XSL中用一个简单的Xpath来做到这一点,但这只是一个例子。
如果我不清楚,请告诉我。
只是为了让舒尔知道你是正确的。您正在尝试通过在Java中选择XPath部分来将Source.xml文件的一部分转换为目标,而不更改源xml或xsl? – treeno
您的xpath在属性:// catalog/cd [@ active ='0']上缺少“@” –
@treeno是的。这是主意。 – Ventura