Robin Olsen Robin Olsen - 6 months ago 41
Java Question

How do I retreive one specific piece of data from a XML file using XMLreader?

A real example of the XML data I have to parse through and how the file is configured. this is how the file is presented to me.

<?xml version="1.0"?>
<value id="FILE_CREATE_DATE">
<value id="LAST_ACCESSED">

I need to go into this file and retrieve the FILE_CREATE_DATE data.

My code so far:

File xmlFile = new File(XMLFileData[i].getPath());
FileInputStream myXMLStream = new FileInputStream(xmlFile);

XMLInputFactory XMLFactory = XMLInputFactory.newInstance();
XMLStreamReader XMLReader = XMLFactory.createXMLStreamReader(myXMLStream);
if (XMLReader.getEventType() == XMLStreamReader.START_ELEMENT)
String XMLTag = XMLReader.getLocalName();

the 'getLocalName()' function returns 'Sessions' then 'value' then 'values' but never returns the actual name of the element. I need to test to see if I am at the right element then retrieve the data from that element...


Your id is not an element - it's element attribute.

You should read attribute of your value node, see the javadoc for getAttributeValue method:,%20java.lang.String)

Returns the normalized attribute value of the attribute with the namespace and localName If the namespaceURI is null the namespace is not checked for equality

So it will be:

String XMLTag = XMLReader.getLocalName();
if(XMLTag.equals("value")) {
   String idValue = XMLReader.getAttributeValue(null, "id");
   //here idValue will be equal to FILE_CREATE_DATE, LAST_ACCESSED or VERSION_TIMESTAMP