我目前正在开发一个图形 XML 编辑器,对于该编辑器,我必须能够通过其 ID 属性访问各个元素。
我已经建立了一个 XML 模式,在其中定义了 ID 属性。
我使用 javax.xml.parsers.DocumentBuilderFactory 并通过相应的 SchemaFactory 为其分配架构。到目前为止,我的 XML 文档的验证也有效,如果不遵循约束,我会收到错误消息。但是 Attr.isId() 始终返回 false。
提示可能是以下错误消息:
错误:URI=null Line=2:文档根元素“TABS”必须与 DOCTYPE 根“null”匹配。
在我看来,解析器正在尝试使用 DTD 而不是模式来验证 XML 文档。
我正在使用Java 1.8。
解析文档并加载架构
public static Document generateDom(IDocument xmlDocument) {
String editorText = xmlDocument.get();
StringReader reader = new StringReader(editorText);
InputSource inputSource = new InputSource(reader);
DocumentBuilderFactory documentFactory = DocumentBuilderFactory.newInstance();
setSchema(documentFactory);
documentFactory.setValidating(true);
Document document = null;
try {
DocumentBuilder builder = documentFactory.newDocumentBuilder();
document = builder.parse(inputSource);
} catch (ParserConfigurationException | SAXException | IOException e) {
// TODO ErrorHandling
e.printStackTrace();
}
return document;
}
private static void setSchema(DocumentBuilderFactory documentFactory) {
URL url = DomLoader.class.getResource("..\\..\\..\\resources\\scriptGenerator.xsd");
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = null;
try {
schema = schemaFactory.newSchema(url);
} catch (SAXException e1) {
// TODO ErrorHandling
e1.printStackTrace();
}
documentFactory.setSchema(schema);
}
模式定义摘录
<xs:element name="GROUP">
<xs:complexType>
<xs:sequence>
<xs:sequence>
<xs:element ref="SQL" />
</xs:sequence>
<xs:sequence minOccurs="0" maxOccurs="unbounded">
<xs:choice>
<xs:element ref="TEXT" />
<xs:element ref="BUTTON" />
<xs:element ref="ALWAYS" />
</xs:choice>
</xs:sequence>
</xs:sequence>
<xs:attribute name="id" use="required" type="xs:ID" />
<xs:attribute name="name" use="required" type="xs:string" />
</xs:complexType>
</xs:element>
我的 .xml 文件
<?xml version="1.0" encoding="UTF-8"?>
<TABS>
<TAB id="ID_ea1270bc-2554-4291-b5ad-8c7802b5fc49" name="Tab 1">
<GROUP id="ID_3155171c-d2ac-4717-aa38-009005c79e18" name="Group 1">
<SQL>
<PREPARE>
<CONSTANT/>
</PREPARE>
<MERGE>
<CONSTANT/>
</MERGE>
<SYNCHRONIZE>
<CONSTANT/>
</SYNCHRONIZE>
</SQL>
</GROUP>
</TAB>
</TABS>
如果使用 Attr.isId(),我的控制台输出:
id | false
name | false
id | false
name | false
id | false
name | false
type | false
好吧,至少我找到了错误的解决方案
Error: URI=null Line=2: Document root element "TABS" must match DOCTYPE root "null"
如果您使用 DocumentFactory.setValidating(true)
DocumentBuilder 实际上需要 DTD 而不是架构。因此,关闭此功能也会使错误消失。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)