我有一个文档,其字符串表示形式为
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<model xmlns="http://magwas.rulez.org/zenta.3.0">
<element id="thing"/>
</model>
xmlDocument.getElementById("thing"
)返回null。
我尝试根据to this answer将id定义为ID字段。
我的模式如下:
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema targetNamespace="http://magwas.rulez.org/zenta.3"
xmlns:zenta="http://magwas.rulez.org/zenta.3" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:complexType name="model">
<xsd:sequence>
<xsd:element maxOccurs="unbounded" minOccurs="0" name="element" type="zenta:element"/>
</xsd:sequence>
</xsd:complexType>
<xsd:complexType name="element">
<xsd:simpleContent>
<xsd:extension base="xsd:string">
<xsd:attribute name="id" use="required" type="xsd:ID"/>
</xsd:extension>
</xsd:simpleContent>
</xsd:complexType>
</xsd:schema>
相关代码:
final public static String XML_SCHEMA = "http://magwas.rulez.org/zenta.3.0";
private static Schema compiledSchema = createSchema();
private static DocumentBuilderFactory factory = createBuilderFactory();
public XmlUtils() {
super();
}
public static Document createDocument() {
DocumentBuilderFactory factory = createBuilderFactory();
DocumentBuilder builder;
try {
builder = factory.newDocumentBuilder();
Schema schema = builder.getSchema();
System.out.printf("schema:%s\n",schema);
return builder.newDocument();
} catch (ParserConfigurationException e) {
throw new ReportedError("cannot create new document", e);
}
}
private static DocumentBuilderFactory createBuilderFactory() {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setSchema(compiledSchema);
factory.setNamespaceAware(true);
factory.setValidating(false);
factory.setNamespaceAware(true);
return factory;
}
private static Schema createSchema() {
SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
Schema compiledSchema;
try {
compiledSchema = schemaFactory.newSchema(XmlUtils.class.getClassLoader()
.getResource("zenta.xsd"));
} catch (SAXException e) {
throw new ReportedError("cannot load zenta schema", e);
}
return compiledSchema;
}
我已经检查过isId()是否为元素的id属性为false。 我还检查了该模式是否已真正解析:如果将其设为无效的xml,则会收到错误消息。
我应该怎么做才能清楚地表明id元素实际上是一个id?