When i try to read Comment's from XML file, Comment's from both the element are printing twice, when it pass through the loop. it should print first element comment in first iteration and second element comment in next iteration. If it is not clear, I have attached expected Output and Actual output for reference.
XML Code:
<shipments>
<shipment id="011">
<department>XXXX</department>
<!-- Product: XXXXX-->
</shipment>
</shipments>
Code:
public class Main {
public static void main(String[] args) throws SAXException,
IOException, ParserConfigurationException, XMLStreamException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// Ignores all the comments described in the XML File
factory.setIgnoringComments(false);
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new File("Details.xml"));
doc.getDocumentElement().normalize();
NodeList ShipmentList = doc.getElementsByTagName("shipment");
for (int i = 0; i < ShipmentList.getLength(); i++)
{
Node node = ShipmentList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE)
{
Element eElement = (Element) node;
XMLStreamReader xr = XMLInputFactory.newInstance().createXMLStreamReader(new FileInputStream("shipmentDetails_1.xml"));
while (xr.hasNext()) {
if (xr.next() == XMLStreamConstants.COMMENT) {
String comment = xr.getText();
System.out.print("Comments: ");
System.out.println(comment);
} }
}
}
}
}
Expected Output:
COMMENTS : Product : Laptop
COMMENTS : Product : Mobile Phone
Output What i am getting:
Comments: Product:Laptop
Comments: Product:Mobile Phone
Comments: Product:Laptop
Comments: Product:Mobile Phone