首页 文章

动态生成XML模式

提问于
浏览
3

我试图使用Xerces-J动态生成XML模式并获得以下错误,感谢任何有关它的帮助 .

DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
dbfac.setNamespaceAware(true);

DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
Document doc = docBuilder.newDocument();

Element schema = doc.createElement("xs:schema");           
schema.setAttribute("xmlns:xs", "http://www.w3.org/2001/XMLSchema");
doc.appendChild(schema);

Element e = doc.createElement("xs:element");            
e.setAttribute("name", "test");
e.setAttribute("type", "xs:string");

schema.appendChild(e);

TransformerFactory transfac = TransformerFactory.newInstance();
Transformer trans = transfac.newTransformer();
trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
trans.setOutputProperty(OutputKeys.INDENT, "yes");

//create string from xml tree
StringWriter sw = new StringWriter();
StreamResult result = new StreamResult(sw);
DOMSource source = new DOMSource(doc);

trans.transform(source, result);
String xmlString = sw.toString();

System.out.println(xmlString);

SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

Schema schema1 = schemaFactory.newSchema(source);

Output is

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="test" type="xs:string"/>
</xs:schema>

org.xml.sax.SAXParseException:s4s-elt-schema-ns:元素'xs:schema'的名称空间必须来自模式名称空间'http://www.w3.org/2001/XMLSchema' .

2 回答

  • 2

    构建DOM时,不要将名称空间指定为属性 . 相反,使用带有两个参数的 createElement() 版本:第一个是命名空间URI,第二个是元素的限定名称 .

    另请注意,限定名称的前缀将自动与名称空间URI匹配 . 如果你愿意,你可以完全消除前缀,并且序列化器将做正确的事情(创建没有前缀的 xmlns 属性,或生成前缀) .

  • 0

    我有类似的问题,发现Apache Commons XMLSchema

相关问题