我已经研究 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
变量。有人可以告诉我正确的方法吗,面向对象的风格?
最佳答案
显然,有很多方法可以做到这一点。我将提供一个提供一种选择的框架。我不会讨论性能或 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
实现。
请注意还要您可能希望如何通过某种配置而不是硬编码来注入(inject) XPath。
再说一次,这并不意味着是理想的或高性能的,而且它实际上可能无法达到您想要的效果。但希望它能为您提供一些有关如何从 OO 角度构建代码的想法。
关于java - Java 的面向对象风格编程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19817090/