Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse XML with SAX in java, case insensitive.

I can parse xml just fine with SAXParserFactory in Java, BUT in some files, there are some non-lowercase attributes present, like linear3D="0.5" etc.

I would like to somehow make

attributes.getValue(attr)

case-insensitive, so that attributes.getValue("linear3d") returns "0.5".

One solution would be to read the file as a string first, convert to lowercase, and then parse, since there is no ambiguity in doing this in this type of xml. However, can this be done more simply, by adding some flag to the factory or similar?

like image 452
Per Alexandersson Avatar asked Oct 10 '22 09:10

Per Alexandersson


1 Answers

Instead of converting the entire file in to lower case the following approach is better. This iterates through all the attributes of the selected tag and comperes it ignoring the case.

Inside the implementaion of DefaultHandler write the following method

private String getValueIgnoreCase(Attributes attributes, String qName){
    for(int i = 0; i < attributes.getLength(); i++){
        String qn = attributes.getQName(i);
        if(qn.equalsIgnoreCase(qName)){
            return attributes.getValue(i);
        }
    }
    return null;
}
like image 104
M S Avatar answered Oct 20 '22 05:10

M S