如何从XSL获取对象列表

时间:2013-05-27 15:30:15

标签: java xml xslt foreach

拜托,我想知道如何从xsl文件中获取java对象列表。

这是文件的一个例子:

//的catalog.xml

<catalog>
    <cd>
        <title>Empire Burlesque</title>
        <artist>Bob Dylan</artist>
        <country>USA</country>
    </cd>
    <cd>
        <title>Hide your heart</title>
        <artist>Bonnie Tyler</artist>
        <country>UK</country>
    </cd>
    <cd>
        <title>Greatest Hits</title>
        <artist>Dolly Parton</artist>
        <country>USA</country>
    </cd>
</catalog>

//在xsl文件中我有:

<xsl:for-each select="catalog/cd">
      <tr>
        <td><xsl:value-of select="title" /></td>
        <td><xsl:value-of select="artist" /></td>
      </tr>
</xsl:for-each>

所以,如果我想获得java类中所有标题的列表,我该怎么办?

换句话说,我想得到(在java类中)一个包含3个值的列表:Empire Burlesque,Hide your heart和Greatest Hit。

提前谢谢

1 个答案:

答案 0 :(得分:0)

也许你可以尝试使用XPath。您可以查询节点的NodeList并获取遍历节点列表的名称

类似的东西:

public NodeList nodeListByXPath(Node xml,
                                String theXPath) throws XPathExpressionException {
NodeList outNodes = (NodeList)_xPath(xml,theXPath,XPathConstants.NODESET);
    return outNodes;
}
private Object _xPath(Node xml,
                  String theXPath,
              QName returnType) throws XPathExpressionException {
    Object outObj = null;
    XPathFactory xPathFactory = XPathFactory.newInstance();
    XPath xPath = xPathFactory.newXPath();
    XPathExpression xPathExpr = xPath.compile(theXPath.trim());
    if (returnType == XPathConstants.BOOLEAN) {
         outObj = xPathExpr.evaluate(xml,XPathConstants.BOOLEAN);
    } else if (returnType == XPathConstants.NUMBER) {
         outObj = xPathExpr.evaluate(xml,XPathConstants.NUMBER);
    } else if (returnType == XPathConstants.STRING) {
         outObj = xPathExpr.evaluate(xml,XPathConstants.STRING);
    } else if (returnType == XPathConstants.NODE) {
         outObj = xPathExpr.evaluate(xml,XPathConstants.NODE);
    } else if (returnType == XPathConstants.NODESET) {
         outObj = xPathExpr.evaluate(xml,XPathConstants.NODESET);
    }
    return outObj;
}
public Document parse(InputStream is)  throws SAXException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setIgnoringComments(true);    
    factory.setValidating(false);         
    factory.setIgnoringElementContentWhitespace(true);
    factory.setNamespaceAware(false);            
    DocumentBuilder builder;
    try {
        builder = factory.newDocumentBuilder();
        InputSource ins = new InputSource(is);
        Document doc = builder.parse(ins);    
        return doc;
    } catch (ParserConfigurationException pcEx) {
        throw new SAXException(pcEx);
    } catch (IOException ioEx) {
        throw new SAXException(ioEx);
    } 
}

您只需致电:

Document doc = parse(is);
NodeList nl = nodeListByXPath(doc.getDocumentElement(),
                              "/catalog/cd/title");

现在遍历节点