我尝试使用以下数据解析xml-feed:
<company>
<year id="2000">
<quarter id="1" sales="80"/>
</year>
<year id="2001">
<quarter id="1" sales="20"/>
</year>
</company>
是否有可能只获得值为2001的年份?
我有以下代码:
URL url = new URL(feedUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream is = conn.getInputStream();
//DocumentBuilderFactory, DocumentBuilder are used for
//xml parsing
DocumentBuilderFactory dbf = DocumentBuilderFactory
.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
//using db (Document Builder) parse xml data and assign
//it to Element
Document document = db.parse(is);
Element element = document.getDocumentElement();
//take rss nodes to NodeList
element.normalize();
NodeList nodeList = ???????
答案 0 :(得分:3)
您可以使用XPath API:
import java.io.StringReader;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;
public class Demo {
public static void main(String[] args) throws Exception {
String xml = "<company><year id='2000'><quarter id='1' sales='80'/></year><year id='2001'><quarter id='1' sales='20'/></year></company>";
String xpath = "/company/year[@id=2001]";
XPath xPath = XPathFactory.newInstance().newXPath();
Node node = (Node) xPath.evaluate(xpath, new InputSource(new StringReader(xml)), XPathConstants.NODE);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer t = tf.newTransformer();
t.transform(new DOMSource(node), new StreamResult(System.out));
}
}
答案 1 :(得分:0)
如果您不想使用XPath,可以执行以下操作:
NodeList list = element.getElementsByTagName("year");
for(int i = 0 ; i < list.getLength(); i++){
Node n = list.item(i);
NamedNodeMap map = n.getAttributes();
String value = map.getNamedItem("id").getNodeValue();
System.out.println(value);
if("2001".equals(value)){
//do something with node n
System.out.println("found");
}
}