[英]Why do I get different results with String.intern() vs. passing String object in Java?
我有一个命令行程序来根据XSD文件验证XML。 此程序的命令行选项之一是要使用的名称空间,该String namespace
存储在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。
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);
}
}
您还需要覆盖endElement()
,其中包含类似的逻辑。 否则,start和end元素URI可能不匹配。 XMLFilterImpl
可能在==而不是.equals()上匹配它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.