我想使用Xerces-J動態生成XML模式並獲取以下錯誤,感謝有關它的任何幫助。動態生成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-架構-NS:元素的命名空間 '的xs:模式' 必須從 架構命名空間,「http://www.w3.org/2001/XMLSchema的」。
感謝您的答覆。我根據您的建議將代碼更改爲Element schema = doc.createElementNS(「http://www.w3.org/2001/XMLSchema」,「xs:schema」);我得到以下錯誤s4s-elt-invalid-content.1:'schema'的內容無效。元素「xs:element」無效,放錯位置或發生頻率過高。 – user1959200
@ user1959200 - 你還更新了創建'element'元素的行嗎? – parsifal
將setElement更改爲setElementNS並將setAttribute更改爲setAttributeNS工作!謝謝 – user1959200