Home > Software engineering >  Java DOM Element, How to find the actual data type of the Element values? As of now everything consi
Java DOM Element, How to find the actual data type of the Element values? As of now everything consi

Time:09-24

I have a custom user-defined section within my standard XML. Something like this:

<rail:JourneyDate>2014-12-12</rail:JourneyDate>
<rail:Name>Rajadhani</rail:Name>
<rail:AxelCount>12</rail:AxelCount>
<rail:VehicleCount>true</rail:VehicleCount>
<rail:PassangerCount>20.5</rail:PassangerCount>

This part of the XML is completely user-defined and can be anything. I am reading it using JAXB and everything is working fine.

The problem is that all the values in the Dom Element are considered as String but as we can see in the above XML the values can be different data types such as Date, Integer, Float, Boolean, String etc.

However when I read the value of each element using element.getTextContent() then this function always returns String. Is there a way to find the actual data type of each Element rather than the String every time?

CodePudding user response:

I created the class to determine the type:

public class ExtensionsDatatypeFinder {

    private ExtensionsDatatypeFinder() {}

    //Method to check the datatype for user extension, ILMD, Error extensions
    public static Object dataTypeFinder(String textContent) {

        if (textContent.equalsIgnoreCase("true") || textContent.equalsIgnoreCase("false")) {
            //Check if the Element Text content is of Boolean type
            return Boolean.parseBoolean(textContent);
        } else if (NumberUtils.isParsable(textContent)) {
            //Check if the Element Text content is Number type if so determine the Int or Float
            return textContent.contains(".") ? Float.parseFloat(textContent) : Integer.parseInt(textContent);
        } else {
            return textContent;
        }
    }
}

Then called it bypassing the required data:

//Check for the datatype of the Element
                final Object simpleFieldValue = ExtensionsDatatypeFinder.dataTypeFinder((String) extension.getValue());

                //Based on the type of Element value write the value into the JSON accordingly
                if (simpleFieldValue instanceof Boolean) {
                    gen.writeBooleanField(extension.getKey(), (Boolean) simpleFieldValue);
                } else if (simpleFieldValue instanceof Integer) {
                    gen.writeNumberField(extension.getKey(), (Integer) simpleFieldValue);
                } else if (simpleFieldValue instanceof Float) {
                    gen.writeNumberField(extension.getKey(), (Float) simpleFieldValue);
                } else {
                    //If instance is String directly add it to the JSON
                    gen.writeStringField(extension.getKey(), (String) extension.getValue());
                }

  • Related