Why am I getting different results using String.intern () against passing a String object in Java?

I have a command line program to validate XML against an XSD file. One of the command line options for this program is the namespace that is stored in String namespace. I get a different check result depending on whether I pass the parsed parameter as quality namespaceor pass the call namespace.intern(). Different results mean that somewhere in the XML validator, comparisons Stringperformed in the namespace have different results, although they must have the same set of ASCII values.

Is there a fundamental reason why they can lead to different comparison results?

The class NamespaceFilter, see below, where the namespace value is used. This class compares namespacewith the value found in the current element inside startElement, and then assigns it. startElementCalled by the XML reader.

These are the line options inside validateAgainstXSD:

String.intern()

NamespaceFilter nsf = new NamespaceFilter(XMLReaderFactory.createXMLReader(), namespace.intern());

Result:
Checking uart.xml.

String object as is

NamespaceFilter nsf = new NamespaceFilter(XMLReaderFactory.createXMLReader(), namespace);

Result:
Error in 4: cvc-complex-type.2.4.a: Invalid content was found starting with the element 'fileVersion'. One of {{myNamespace ": fileVersion} is expected.

Source in context

public static void validateAgainstXSD(File file, File schemaFile, String namespace) {

    try {
        SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");

        Schema xsdScheme = factory.newSchema(schemaFile);

        Validator validator = xsdScheme.newValidator();
        ErrorHandler eh = new DefaultErrorHandler();

        validator.setErrorHandler(eh);

        // Create namespace replacement filter  
        NamespaceFilter nsf = new NamespaceFilter(XMLReaderFactory.createXMLReader(), namespace.intern());

        // Load the XML source
        SAXSource source = new SAXSource(nsf, new InputSource(new FileInputStream(file)));

        validator.validate(source, null);
    } catch (Exception e) {
        e.printStackTrace();
    }

}

private static class NamespaceFilter extends XMLFilterImpl {

    private String requiredNamespace;

    public NamespaceFilter(XMLReader parent) {
        super(parent);
    }

    public NamespaceFilter(XMLReader parent, String namespace) {
        this(parent);

        requiredNamespace = namespace;
    }

    @Override
    public void startElement(String uri,
            String localName,
            String qName,
            Attributes atts)
            throws SAXException {

        if (!uri.equals(requiredNamespace)) {
            uri = requiredNamespace;
        }
        super.startElement(uri, localName, qName, atts);

    }
}
+5
source share
1 answer

endElement(), . URI . XMLFilterImpl, , ==, .equals().

+1

All Articles