我几天来一直在研究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中工作,我不担心面向对象编程,但是,我真的想将这些变为static
或public
变量。有人能告诉我这样做的正确方法,面向对象的风格吗?
答案 0 :(得分: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相关数据。客户不关心,也不应该知道数据格式是什么或者如何处理。
另请注意我如何返回List
而不是ArrayList
。您的客户甚至不应该知道使用了哪个List
实现。
注意也你可能希望通过某种配置注入XPath而不是硬编码。
同样,这并不意味着理想或高效,也可能实际上并不是你想要的。但希望它能为您提供有关如何从OO角度构建代码的一些想法。