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
To get the values from the XML declaration, call the following methods on the Document
:
getXmlEncoding()
- An attribute specifying, as part of the XML declaration, the encoding of this document. This isnull
when unspecified or when it is not known, such as when theDocument
was created in memory.getXmlStandalone()
- An attribute specifying, as part of the XML declaration, whether this document is standalone. This isfalse
when unspecified.getXmlVersion()
- An attribute specifying, as part of the XML declaration, the version number of this document. If there is no declaration and if this document supports the "XML" feature, the value is"1.0"
.
UPDATED
To find and print comments inside the <shipment>
element, iterate the child nodes of the element and look for nodes of type COMMENT_NODE
, cast it to a Comment
, and print the value of getData()
.
for (Node child = node.getFirstChild(); child != null; child = child.getNextSibling()) {
if (child.getNodeType() == Node.COMMENT_NODE) {
Comment comment = (Comment) child;
System.out.println("COMMENTS : " + comment.getData());
}
}
To clarify: The node
used here is from the question code. You can also use eElement
instead of node
. Makes no difference.