开发者

Parsing xml with dom4j or jdom or anyhow

I wanna read feed entries and I'm just stuck now. Take this for example : https://stackoverflow.com/feeds/question/2084883 lets say I wanna read all the summary node value inside each entry node in document. How do I do that? I've changed many variations of code this one is closest to what I want to achieve I think :

Element entryPoint = document.getRootElement();
  Element elem;
  for(Iterator iter = entryPoint.elements().iterator(); iter.hasNext();){
   elem = (Element)iter.next();
                    System.out.println(elem.getName());
  }

It goes trough all nodes in xml file and writes their name. Now what I wanted to do next is

if(elem.getName().equals("entry"))

to get only the entry nodes, how do I get elements of the entry nodes, and how to get let say summary and its value? tnx

Question: how to get values of summary nodes from thi开发者_JS百科s link


Have you tried jdom? I find it simpler and convenient.

http://www.jdom.org/

To get all children of an xml element, you can just do

SAXBuilder sb = new SAXBuilder();
            StringReader sr = new StringReader(xmlDocAsString);
            Document doc = sb.build(sr);
            Element root = doc.getRootElement();
            List l = root.getChildren("entry");
            for (Iterator iter = l.iterator(); iter.hasNext();) {
...//do whatever...
}


Here's how you'd do it using vanilla Java:

//read the XML into a DOM
StreamSource source = new StreamSource(new StringReader("<theXml></theXml>"));
DOMResult result = new DOMResult();
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.transform(source, result);
Node root = result.getNode();

//make XPath object aware of namespaces
XPath xpath = XPathFactory.newInstance().newXPath();
xpath.setNamespaceContext(new NamespaceContext(){
    @Override
    public String getNamespaceURI(String prefix) {
        if ("atom".equals(prefix)){
            return "http://www.w3.org/2005/Atom";
        }
        return null;
    }

    @Override
    public String getPrefix(String namespaceURI) {
        return null;
    }

    @Override
    public Iterator getPrefixes(String namespaceURI) {
        return null;
    }
});

//get all summaries
NodeList summaries = (NodeList) xpath.evaluate("/atom:feed/atom:entry/atom:summary", root, XPathConstants.NODESET);
for (int i = 0; i < summaries.getLength(); ++i) {
    Node summary = summaries.item(i);

    //print out all the attributes
    for (int j = 0; j < summary.getAttributes().getLength(); ++j) {
        Node attr = summary.getAttributes().item(j);
        System.out.println(attr.getNodeName() + "=" + attr.getNodeValue());
    }

    //print text content
    System.out.println(summaries.item(i).getTextContent());
}


if(elem.getName() == "entry")

I have no idea whether this is your problem (you don't really state what your problem is), but never test string equality with --. Instead, use equals():

if(elem.getName().equals("entry"))


A bit late but it might be useful for people googling...

There is a specialized API for dealing with RSS and Atom feeds in Java. It's called Rome, can be found here :

http://java.net/projects/rome/

It is really quite useful, it makes easy to read feed whatever the RSS or Atom version. You can also build feeds and generate the XML with it though I have no experience with this feature.

Here is a simple example that reads a feed and prints out the description nodes of all the entries in the feed :

URL feedSource = new URL("http://....");
feed = new SyndFeedInput().build(new XmlReader(feedSource));
List<SyndEntryImpl> entries = (List<SyndEntryImpl>)feed.getEntries();

for(SyndEntryImpl entry : entries){
    System.out.println(entry.getDescription().getValue());
}

Simple enough.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜