为什么我使用String.intern()与在Java中传递String对象获得不同的结果?

ste*_*ver 5 java

我有一个命令行程序来根据XSD文件验证XML.此程序的命令行选项之一是要使用的命名空间,存储在其中String namespace.我得到一个不同的验证结果取决于我是否将解析的选项作为namespace传递或传递给namespace.intern().不同的结果意味着在XML验证器中的某处,String对命名空间执行的比较具有不同的结果,即使它们应具有相同的ASCII值集.

有没有一个根本原因可能会产生不同的比较结果?

NamespaceFilter班,看到下面,是被使用的命名空间值,其中.此类与namespace在当前元素内找到的值进行比较startElement,然后分配它. startElement由XML阅读器调用.

以下是validateAgainstXSD中的行变化:

String.intern()

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

结果:
验证uart.xml.

String对象不变

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

结果:
错误为4:cvc-complex-type.2.4.a:从元素'fileVersion'开始发现无效内容.其中一个'{"myNamespace":fileVersion}'是预期的.

来源于上下文

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);

    }
}
Run Code Online (Sandbox Code Playgroud)

use*_*421 1

endElement()您还需要使用类似的逻辑进行重写。否则,开始和结束元素 URI 可能不匹配。XMLFilterImpl可能是在 == 而不是 .equals() 上匹配它们。