使用dom解析gdata xml

时间:2012-02-14 18:53:35

标签: java xml parsing gdata

我正在寻找一种从youtube video gdata获取关键字的方法。

xml看起来如下所示:

<?xml version='1.0' encoding='UTF-8'?>
<entry xmlns='http://www.w3.org/2005/Atom' xmlns:media='http://search.yahoo.com/mrss/' xmlns:gd='http://schemas.google.com/g/2005' xmlns:yt='http://gdata.youtube.com/schemas/2007'>
<id>http://gdata.youtube.com/feeds/api/videos/vidid</id>
<category scheme='http://gdata.youtube.com/schemas/2007/categories.cat' term='Comedy' label='Comedy'/>

<category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='kw1'/>
<category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='kw2'/>
<category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='kw3'/>
<category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='kw4'/>
<category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='kw5'/>

<title type='text'>vid title</title>
...
</entry>

我在某些地方剪了一些东西,所以我可以使用以下代码获得标题:

public static String getTitle(String id) throws IOException, ParserConfigurationException, XPathExpressionException, SAXException {


    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse("https://gdata.youtube.com/feeds/api/videos/" + id);

    XPathFactory xPathfactory = XPathFactory.newInstance();
    XPath xpath = xPathfactory.newXPath();
    XPathExpression expr = xpath.compile("//entry/title/text()");

    Object result = expr.evaluate(doc, XPathConstants.STRING);
    String title = (String) result;
    return title;
}

有没有办法修改它来获取关键字呢? 我应该提一下,可以有任意数量的关键字,而不仅仅是5,如上所示。

1 个答案:

答案 0 :(得分:1)

感谢回复人们。我自己破解了一些似乎可以解决的问题

   public static ArrayList getTags(String id) throws IOException, ParserConfigurationException, XPathExpressionException, SAXException {
    ArrayList<String> tags = new ArrayList<String>();

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse("https://gdata.youtube.com/feeds/api/videos/" + id);
    NodeList nl = doc.getElementsByTagName("category");

    for (int i = 0; i<nl.getLength(); i++) {
        String kwCheck = "http://gdata.youtube.com/schemas/2007/keywords.cat";
        if (kwCheck.equals(nl.item(i).getAttributes().getNamedItem("scheme").getNodeValue()) ) {
            String kw = nl.item(i).getAttributes().getNamedItem("term").getNodeValue();       
            tags.add(kw);
        }
    }

    return tags;
}

这仅返回关键字,但可能会进行一些整理。你们有没有看到这个方法的任何问题?再次感谢