2

几天来,我一直在研究 XML 解析器,并且main大部分时间都在为整个项目工作。代码开始变得混乱,我有一些问题。

// Initializes the xPath objects for XML parsing use
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();

XPathExpression hourly = xpath.compile("/dwml/data/time-layout[3]/start-valid-time/text()"); // Time tri-hourly. Parses in the third time-layout, as this is the time information we need
XPathExpression tempHourly = xpath.compile("/dwml/data/parameters/temperature[@type='hourly']/value/text()"); // Temperature tri-hourly. Parses in through the 'hourly' temperature attribute
XPathExpression dewPoint = xpath.compile("/dwml/data/parameters/temperature[@type='dew point']/value/text()"); // Dew point tri-hourly. Parses in through the 'dew point' temperature attribute
XPathExpression windSpeed = xpath.compile("/dwml/data/parameters/wind-speed[@type='sustained']/value/text()"); // Sustained wind speed tri-hourly. Parses in through the 'sustained' wind-speed attribute
XPathExpression relHum = xpath.compile("/dwml/data/parameters/humidity[@type='relative']/value/text()"); // Relative humidity tri-hourly. Parses in through the 'relative' humidity attribute

// Casting the objects to NodeLists
NodeList hourlyResult = (NodeList) hourly.evaluate(doc,XPathConstants.NODESET);
NodeList tempHourlyResult = (NodeList) tempHourly.evaluate(doc,XPathConstants.NODESET);
NodeList dewPointResult = (NodeList) dewPoint.evaluate(doc,XPathConstants.NODESET); 
NodeList windSpeedResult = (NodeList) windSpeed.evaluate(doc,XPathConstants.NODESET);
NodeList relHumResult = (NodeList) relHum.evaluate(doc,XPathConstants.NODESET);

在 main 工作时,我不担心面向对象的编程,但是,我真的很想将这些更改为staticorpublic变量。有人可以告诉我正确的方法,面向对象的风格吗?

4

1 回答 1

3

显然,有很多方法可以做到这一点。我将提供一个提供一个选项的骨架。我不会处理性能或 XPath 处理的变幻莫测。这是为了说明类设计的想法。

考虑一个专门用于处理 XML 文档的类:

class XMLProcessor { //By the way, that is a terrible name, but I will let you deal with that.
  private static final String HOURS_XPATH = "/dwml/data/time-layout[3]/start-valid-time/text()";
  private XPathFactory xPathfactory = XPathFactory.newInstance();
  private XPathExpression hourly;

  public XMLProcessor(String url) {
    XPath xpath = xPathfactory.newXPath(); 
    hourly = xpath.compile(HOURS_XPATH); 
  }   

  public List<String> getHours() {
    //Pass hourly to toNodeList and turn it to an ArrayList
    //Provide similar methods for all the other data sets you want to extract and provide
  }

  private NodeList toNodeList(XPathExpression exp) {
    //to be reused for all the conversions
    return (NodeList) exp.evaluate(doc,XPathConstants.NODESET);
  }
}

然后在main你做类似的事情

XMLProcessor x = new XMLProcessor(url);
List<String> = x.getHours();

请注意,main在这种情况下,客户端不知道XMLProcessor正在执行与 XPath 相关的任何操作。它传递一个 URL 并返回与 XML 无关的数据。客户端不关心也不应该知道数据格式是什么或它是如何处理的。

另请注意我如何返回 aList而不是ArrayList. 您的客户甚至不应该知道List使用了哪个实现。

还要注意您可能希望如何通过某种配置而不是硬编码来注入您的 XPath。

同样,这并不意味着是理想的或高性能的,它实际上可能不会做你想要的。但希望它能给您一些关于如何从 OO 角度构建代码的想法。

于 2013-11-06T16:44:29.443 回答