解析 XML 和检索信息 多层节点 Deep Java/Android

发布于 2024-10-06 18:16:52 字数 2265 浏览 5 评论 0原文

我正在使用我的教授提供的一个示例,该示例从天气预报站点获取数据并解析 XML 文件以在列表中显示天气状况。我的程序类似,但我想检索嵌套在多个节点中的信息,但我不知道如何获取它。这是我正在处理的 XML 文件:

<?xml version="1.0" encoding="UTF-8"?> 
<DirectionsResponse> 
 <status>OK</status> 
 <route> 
  <summary>S Street Viaduct</summary> 
  <leg> 
   <step> 
    <travel_mode>DRIVING</travel_mode> 
    <start_location> 
     <lat>40.7021400</lat> 
     <lng>-74.0158200</lng> 
    </start_location> 
    <end_location> 
     <lat>40.7021400</lat> 
     <lng>-74.0158200</lng> 
    </end_location> 
    <polyline> 
     <points>kslwFzewbM</points> 
     <levels>B</levels> 
    </polyline> 
    <duration> 
     <value>0</value> 
     <text>1 min</text> 
    </duration> 
    <html_instructions>Head &lt;b&gt;east&lt;/b&gt; on &lt;b&gt;S Street Viaduct&lt;/b&gt;</html_instructions> 
    <distance> 
     <value>0</value> 
     <text>1 ft</text> 
    </distance> 
   </step> 
   <duration> 
    <value>0</value> 
    <text>1 min</text> 
   </duration> 
   <distance> 
    <value>0</value> 
    <text>1 ft</text> 
   </distance> 
   <start_location> 
    <lat>40.7021400</lat> 
    <lng>-74.0158200</lng> 
   </start_location> 
   <end_location> 
    <lat>40.7021400</lat> 
    <lng>-74.0158200</lng> 
   </end_location> 
   <start_address>S Street Viaduct, New York, NY 10004, USA</start_address> 
   <end_address>S Street Viaduct, New York, NY 10004, USA</end_address> 
  </leg> 
  <copyrights>Map data ©2010 Google, Sanborn</copyrights> 
  <overview_polyline> 
   <points>kslwFzewbM</points> 
   <levels>B</levels> 
  </overview_polyline> 
 </route> 
</DirectionsResponse> 

我真的只对检索“html_instructions”标签中的信息感兴趣,但它嵌套在“route”、“leg”和“step”标签中。我看过一些关于解析 XML 的教程和问题,但似乎找不到解决方案。任何方向将不胜感激!

谢谢。

I am working from an example provided by my professor which gets data from a weather forecast site and parses the XML file to show the weather conditions in a list. My program is similar, but I want to retrieve information that is nested within several nodes, and I don't know how to get to it. Here is the XML file I'm working from:

<?xml version="1.0" encoding="UTF-8"?> 
<DirectionsResponse> 
 <status>OK</status> 
 <route> 
  <summary>S Street Viaduct</summary> 
  <leg> 
   <step> 
    <travel_mode>DRIVING</travel_mode> 
    <start_location> 
     <lat>40.7021400</lat> 
     <lng>-74.0158200</lng> 
    </start_location> 
    <end_location> 
     <lat>40.7021400</lat> 
     <lng>-74.0158200</lng> 
    </end_location> 
    <polyline> 
     <points>kslwFzewbM</points> 
     <levels>B</levels> 
    </polyline> 
    <duration> 
     <value>0</value> 
     <text>1 min</text> 
    </duration> 
    <html_instructions>Head <b>east</b> on <b>S Street Viaduct</b></html_instructions> 
    <distance> 
     <value>0</value> 
     <text>1 ft</text> 
    </distance> 
   </step> 
   <duration> 
    <value>0</value> 
    <text>1 min</text> 
   </duration> 
   <distance> 
    <value>0</value> 
    <text>1 ft</text> 
   </distance> 
   <start_location> 
    <lat>40.7021400</lat> 
    <lng>-74.0158200</lng> 
   </start_location> 
   <end_location> 
    <lat>40.7021400</lat> 
    <lng>-74.0158200</lng> 
   </end_location> 
   <start_address>S Street Viaduct, New York, NY 10004, USA</start_address> 
   <end_address>S Street Viaduct, New York, NY 10004, USA</end_address> 
  </leg> 
  <copyrights>Map data ©2010 Google, Sanborn</copyrights> 
  <overview_polyline> 
   <points>kslwFzewbM</points> 
   <levels>B</levels> 
  </overview_polyline> 
 </route> 
</DirectionsResponse> 

I'm really only interested in retrieving the info in the "html_instructions" tag, but it is nested in the "route", "leg", and "step" tags. I have seen several tutorials and questions on SO about parsing XML but couldn't seem to find a solution to this. Any direction would be greatly appreciated!

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

夏尔 2024-10-13 18:16:52

所以基本上使用 SAX 解析器对你来说是一个不错的选择(它速度快,允许你过滤掉所有不必要的数据,消耗低内存)。当第一次使用 SAX 时,您可能会发现以下示例很有用。我并不是说代码是完美的(它错过了异常处理、安全流关闭等),但它可能是您的一个很好的起点。


import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class Test {

  private static final String HTML_INSTRUCTIONS = "html_instructions";

  public static void main(String[] args) throws Exception {
    final List htmlInstructions = new ArrayList();

    SAXParserFactory spf = SAXParserFactory.newInstance();
    SAXParser sp = spf.newSAXParser();
    DefaultHandler dh = new DefaultHandler() {
      private boolean isHtmlInstructions = false;
      private StringBuilder sb = new StringBuilder();
      @Override
      public void startElement(String uri, String localName, String name,
          Attributes attributes) throws SAXException {
        super.startElement(uri, localName, name, attributes);
        if (HTML_INSTRUCTIONS.equals(name)) {
          isHtmlInstructions = true;
        }
      }

      @Override
      public void characters(char ch[], int start, int length)
      throws SAXException {
        if (isHtmlInstructions) {
          sb.append(ch, start, length);
        }
      }

      @Override
      public void endElement(String uri, String localName, String name)
          throws SAXException {
        super.endElement(uri, localName, name);
        if (HTML_INSTRUCTIONS.equals(name)) {
          htmlInstructions.add(sb.toString());
          sb.delete(0, sb.length());
          isHtmlInstructions = false;
        }
      }
    };

    InputStream is = new FileInputStream("test.xml");
    sp.parse(is, dh);
    for (String htmlInstruction : htmlInstructions) {
      System.out.println(htmlInstruction);
    }

  }

}

输出应如下所示:


Head <b>east on <b>S Street Viaduct</b>

So basically using the SAX parser is a good choice for you (it is fast, allows you to filter out all the unnecessary data, consumes low memory). When working with SAX for the first time, you may find the following example useful. I do not say the code is perfect (it misses e.g. exception handling, safe stream closing, etc.), but it could be a good start point for you.


import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class Test {

  private static final String HTML_INSTRUCTIONS = "html_instructions";

  public static void main(String[] args) throws Exception {
    final List htmlInstructions = new ArrayList();

    SAXParserFactory spf = SAXParserFactory.newInstance();
    SAXParser sp = spf.newSAXParser();
    DefaultHandler dh = new DefaultHandler() {
      private boolean isHtmlInstructions = false;
      private StringBuilder sb = new StringBuilder();
      @Override
      public void startElement(String uri, String localName, String name,
          Attributes attributes) throws SAXException {
        super.startElement(uri, localName, name, attributes);
        if (HTML_INSTRUCTIONS.equals(name)) {
          isHtmlInstructions = true;
        }
      }

      @Override
      public void characters(char ch[], int start, int length)
      throws SAXException {
        if (isHtmlInstructions) {
          sb.append(ch, start, length);
        }
      }

      @Override
      public void endElement(String uri, String localName, String name)
          throws SAXException {
        super.endElement(uri, localName, name);
        if (HTML_INSTRUCTIONS.equals(name)) {
          htmlInstructions.add(sb.toString());
          sb.delete(0, sb.length());
          isHtmlInstructions = false;
        }
      }
    };

    InputStream is = new FileInputStream("test.xml");
    sp.parse(is, dh);
    for (String htmlInstruction : htmlInstructions) {
      System.out.println(htmlInstruction);
    }

  }

}

The output should look like this:


Head <b>east on <b>S Street Viaduct</b>

梦里寻她 2024-10-13 18:16:52

使用SAX并且只关注html_instructions标签。将为每个元素使用 startElement() 调用您的处理程序,并传入元素的名称。将该名称与“html_instructions” 进行比较。当您有匹配项时,请注意所有已处理的节点,直到相应的 endElement() 调用。

Use SAX and only pay attention to the html_instructions tag. Your handler will be called with startElement() for each element and is passed in the element's name. Compare that name to "html_instructions". When you have a match, pay attention to all processed nodes until the corresponding endElement() call.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文