0

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

这是文件的一个例子:

//目录.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。

先感谢您

4

1 回答 1

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");

现在遍历节点

于 2013-05-27T16:38:35.633 回答