我有XSD描述自定义架构并导入XLink(另一个架构)。
使用以下声明ix主XSD进行导入:
<xs:import namespace="http://www.w3.org/1999/xlink" schemaLocation="xlink.xsd"/>
xlink.xsd
文件实际上位于主XSD附近。
然后我使用以下代码配置构建器
static final String JAXP_SCHEMA_LANGUAGE = "http://java.sun.com/xml/jaxp/properties/schemaLanguage";
static final String W3C_XML_SCHEMA = "http://www.w3.org/2001/XMLSchema";
static final String JAXP_SCHEMA_SOURCE = "http://java.sun.com/xml/jaxp/properties/schemaSource";
static final String MY_SCHEMA_FILENAME = "mydir/myfile.xsd";
static final String MY_DATA_FILENAME = "mydir/myfile.xml";
factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
factory.setValidating(true);
try {
factory.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
factory.setAttribute(JAXP_SCHEMA_SOURCE, new File(MY_SCHEMA_FILENAME));
}
catch (IllegalArgumentException e) {
throw new AssertionError(e);
}
try {
builder = factory.newDocumentBuilder();
}
catch(ParserConfigurationException e) {
throw new AssertionError(e);
}
当我在内存中准备文档时,我按以下方式设置属性
imageElement.setAttribute("xlink:href", mypathvariable);
我希望这会创建在XSD
<xs:element name="image">
<xs:complexType>
<xs:attribute ref="xlink:href" use="required"/>
</xs:complexType>
</xs:element>
虽然创建一切都没有任何错误,但在使用代码保存时
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(MY_DATA_FILENAME));
transformer.transform(source, result);
发生以下错误:
ERROR: 'Namespace for prefix 'xlink' has not been declared.'
我的错误在哪里?
答案 0 :(得分:1)
使用setAttributeNS代替,如下所示:
imageElement.setAttributeNS("http://www.w3.org/1999/xlink", "href", mypathvariable);
如果你想坚持:
imageElement.setAttribute("xlink:href", mypathvariable);
然后确保在一个为您的属性添加位置提供范围的元素上定义了这个(通常在根元素上):
someElement.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xlink", "http://www.w3.org/1999/xlink");
以上还说明了如何控制前缀。