【问题标题】:XML response how to assign values to variablesXML响应如何为变量赋值
【发布时间】:2012-05-19 08:04:14
【问题描述】:

我得到了 http 请求的 xml 响应。我将其存储为字符串变量

String str = in.readLine();

str的内容是:

<response>
    <lastUpdate>2012-04-26 21:29:18</lastUpdate>
    <state>tx</state>
    <population>
       <li>
           <timeWindow>DAYS7</timeWindow>
           <confidenceInterval>
              <high>15</high>
              <low>0</low>
           </confidenceInterval>
           <size>0</size>
       </li>
    </population>
</response>

我想将txDAYS7 分配给变量。我该怎么做?

谢谢

【问题讨论】:

  • 如果您还告诉我们您正在使用哪种编程语言,我们会更容易为您提供帮助。
  • 您好,对不起,我使用的是 java
  • Xpath 是一种完成它的方法

标签: java xml


【解决方案1】:

http://www.mkyong.com/java/how-to-read-xml-file-in-java-sax-parser/的代码稍作修改

public class ReadXMLFile {

    // Your variables
    static String state;
    static String timeWindow;

    public static void main(String argv[]) {

        try {

            SAXParserFactory factory = SAXParserFactory.newInstance();
            SAXParser saxParser = factory.newSAXParser();

            // Http Response you get
            String httpResponse = "<response><lastUpdate>2012-04-26 21:29:18</lastUpdate><state>tx</state><population><li><timeWindow>DAYS7</timeWindow><confidenceInterval><high>15</high><low>0</low></confidenceInterval><size>0</size></li></population></response>";

            DefaultHandler handler = new DefaultHandler() {

                boolean bstate = false;
                boolean tw = false;

                public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {

                    if (qName.equalsIgnoreCase("STATE")) {
                        bstate = true;
                    }

                    if (qName.equalsIgnoreCase("TIMEWINDOW")) {
                        tw = true;
                    }

                }

                public void characters(char ch[], int start, int length) throws SAXException {

                    if (bstate) {
                        state = new String(ch, start, length);
                        bstate = false;
                    }

                    if (tw) {
                        timeWindow = new String(ch, start, length);
                        tw = false;
                    }
                }

            };

            saxParser.parse(new InputSource(new ByteArrayInputStream(httpResponse.getBytes("utf-8"))), handler);

        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("State is " + state);
        System.out.println("Time windows is " + timeWindow);
    }

}

如果您将其作为某个进程的一部分运行,您可能希望从 DefaultHandler 扩展 ReadXMLFile

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-02
    • 2016-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-28
    • 2015-01-11
    • 1970-01-01
    相关资源
    最近更新 更多