java - xml dom解析器在java中按名称查找标签

标签 java xml parsing dom

我有一个 xml: http://netmobileag.accu-weather.com/widget/netmobileag/weather-data.asp?slat=48.04960&slon=21.71420&metric=1

我只想获取城市和温度,我试过这个:

HttpParams httpParameters = new BasicHttpParams();

HttpClient httpclient = new DefaultHttpClient(httpParameters);
HttpGet httpget = new HttpGethttp://netmobileag.accu weather.com/widget/netmobileag/weather-data.asp?slat=48.04960&slon=21.71420&metric=1");

HttpResponse response = httpclient.execute(httpget);

InputStream in = response.getEntity().getContent();

String res = "";

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(in));
doc.getDocumentElement().normalize();

NodeList loc = doc.getElementsByTagName("local");

for (int i = 0; i < loc.item(0).getChildNodes().getLength(); i++) {
    res = res + "\n" + loc.item(0).getChildNodes().item(0).getNodeValue();
}

但是res会是

#text
#text
 ...

摘要 25x。如何获取城市和温度值?

最佳答案

这里正确的做法是实际使用 Xpath。您是使用 Regex 还是 SQL 在数据库中进行搜索?同样,在 XML 文件中搜索是通过 XPath 完成的。

 package xpath;

 import javax.xml.parsers.DocumentBuilder;
 import javax.xml.parsers.DocumentBuilderFactory;
 import javax.xml.xpath.XPath;
 import javax.xml.xpath.XPathConstants;
 import javax.xml.xpath.XPathExpression;
 import javax.xml.xpath.XPathFactory;

 import org.w3c.dom.Document;
 import org.w3c.dom.NodeList;

 public class SimpleParsing {
public static void main(String[] args) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(false); // never forget this!
    DocumentBuilder builder = factory.newDocumentBuilder();

    Document doc = builder.parse("/Users/eugenrabii/Desktop/MyFile.xml");

    XPathFactory xPathFactory = XPathFactory.newInstance();
    XPath xpath = xPathFactory.newXPath();

    XPathExpression xPathExpression = xpath.compile("//city/text()");

    Object result = xPathExpression.evaluate(doc, XPathConstants.NODESET);

    System.out.println(result.toString());

    NodeList nodes = (NodeList) result;

    System.out.println(nodes.getLength());
    for (int i = 0; i < nodes.getLength(); i++) {
        System.out.println(nodes.item(i).getNodeValue()); 
    }
}

关于java - xml dom解析器在java中按名称查找标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11800931/

相关文章:

java - Spring MVC 抽象类绑定(bind)

java - Vertx 和 JavaFx

css - 使用 XSLT 格式化表格内的虚线

xml - 如何找到计数最高的节点?

C# 如何使用 Linq 解析 Object[] 以查找所有 List<Int> 对象?

java - 静态 Java 命令行解析器的生成器

java - 找不到比较器

java - 加载图像时出错 - "Bitmap size exceeds VM budget"

java - Jaxb 编码 - 从 java 对象获取 xml 中的所有字段

JavaScript:解析 bool