我们必须从为一堆气象站创建假天气数据的生成器中解析 xml 信息。目前我们只是打印它,但我们稍后将不得不对其进行处理。但是,我们收到的数据由多个 XML“文件”组成。有没有办法分离数据并将其拆分为新的<?xml...?>
?(数据是一个随机分裂的连续流)我们的代码:
public class Main {
static private final int portNumber = Null;
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(portNumber);
Socket clientSocket = serverSocket.accept();
BufferedReader clientReader = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
XMLInputFactory factory = XMLInputFactory.newInstance();
XMLStreamReader reader = factory.createXMLStreamReader(clientReader);
while (reader.hasNext()) {
int event = reader.next();
if (event == XMLStreamConstants.START_ELEMENT) {
try {
String text = reader.getElementText();
System.out.println("Element Local Name:" + reader.getLocalName());
System.out.println("Text:" + text);
} catch (XMLStreamException e) {
System.out.println(e);
}
}
else if(event == XMLStreamConstants.END_ELEMENT){
reader.close();
}
}
} catch (IOException e) {
System.out.println("Error: Unable to Start Server Socket\n\t" + e);
} catch (XMLStreamException e){
System.out.println(e);
}
}
}
xml 的示例(我们一个接一个地收到多个):
<?xml version="1.0"?>
<!-- The WEATHERDATA-element contains multiple MEASUREMENT-elements -->
<WEATHERDATA>
<MEASUREMENT>
<STN>123456</STN>
<DATE>2009-09-13</DATE>
<TIME>15:59:46</TIME>
<TEMP>-60.1</TEMP>
<DEWP>-58.1</DEWP>
<STP>1034.5</STP>
<SLP>1007.6</SLP>
<VISIB>123.7</VISIB>
<WDSP>10.8</WDSP>
<PRCP>11.28</PRCP>
<SNDP>11.1</SNDP>
<FRSHTT>010101</FRSHTT>
<CLDC>87.4</CLDC>
<WNDDIR>342</WNDDIR>
</MEASUREMENT>
</WEATHERDATA>
我们也有一个 dtd 文件,但我不确定这是否有帮助。