【发布时间】:2021-08-13 16:06:51
【问题描述】:
我不确定这是否可能,所以无论如何我都想询问并澄清,因为即使经过大量搜索和尝试,我也无法在这里找到类似的东西。如果发现重复真的很抱歉。
我正在尝试使用 XMLStreamReader 解析 XML 文件。阅读后,我必须对我的localpart 进行一些检查,据此我需要将这个XMLStreamReader 分配给不同的类。
当我进行少量检查时,我需要检查current localpart 和next localpart。当我尝试检查next localpart 时,我正在前进到XMLStreamReader 上的next 元素。所以我试图将current XMLStreamReader 存储在另一个temp XMLStreamReader 中,但是在分配之后,当我尝试导航到current XMLStreamReader 上的下一个时,即使temp XMLStreamReader 也在发生变化,我想这是因为我无法执行一些操作的动作。主要是我想执行JAXB Unmarshalling,在此期间它失败了,因为它无法获取类的所有元素。
我知道XMLEventReader 有peek(),但这也失败了,所以我试图存储current XMLStreamReader,但它也不起作用,我读到它不是最有效的内存。由于我的 XML 文件可能非常大,我正在尝试使用 XMLStreamReader。
public class Main
{
public static void main(String[] args) {
final InputStream inputStream = Main.class.getClassLoader().getResourceAsStream("Customer.xml");
final XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
final XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(xmlStream);
//final JAXBContext jaxbContext = JAXBContext.newInstance("io.model.jaxb");
//final Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
//Navigate to next and start of the XML Elements
xmlStreamReader.next();
//Read Until the end of the file
while (xmlStreamReader.hasNext()) {
//Check if the current `XML Tag` is "extension"
if (xmlStreamReader.isStartElement() && xmlStreamReader.getLocalName().equalsIgnoreCase("extension")) {
//Create a tempStream to store the current stream values
//final XMLStreamReader streamReader = xmlInputFactory.createXMLStreamReader((InputStream) xmlStreamReader);
final XMLStreamReader tempReader = xmlStreamReader;
xmlStreamReader.next();
//If the next element is "nextextension"
if (xmlStreamReader.isStartElement() && xmlStreamReader.getLocalName().equalsIgnoreCase("nextextension")) {
System.out.println("Double Extension Assign to CLASS C with both extension tag");
//final C cInfo = unmarshaller.unmarshal(streamReader, C.class).getValue();
}else{
System.out.println("Single Extension Assign to CLASS B with single extension tag");
//final B cInfo = unmarshaller.unmarshal(streamReader, B.class).getValue();
}
}
//Move to the next
xmlStreamReader.next();
}
}
}
我希望我能够解释这个问题。我只想知道是否有办法实现以下任何一项:
- 将
current XMLStreamReader暂时存放在另一个temp XMLStreamReader中,以备日后使用。 - 如果有其他方法可以将
peek()改成next localpart内的XMLStreamReader。
如果我从昨天开始就陷入了这个问题,因此能从这里获得专家的意见真是太好了。
【问题讨论】:
-
您使用的是哪个版本的 Java?我认为这在很长一段时间内都没有改变(自 v8 以来?),但最好清楚一点。
-
非常感谢您的时间和回复。我正在使用最新的
JDK 15。实际上,经过大量尝试和研究,我能够使用MutableXMLStreamBuffer做到这一点。
标签: java xml-parsing jaxb stax xmlstreamreader