[英]Augment XML with XML Schema
javax.xml.validation.Validator具有一種針對模式驗證和擴充xml的方法 。
簡化的xml:
<something>
<sub1>false</sub1> <!-- Suppose sub1 is optional and may not be present in xml -->
<sub2>false</sub2>
</something>
簡化的xsd:
<complexType name="something">
<sequence>
<element name="sub1" type="boolean" maxOccurs="1" minOccurs="0" default="false"/>
<element name="sub2" type="boolean" maxOccurs="1" minOccurs="1"/>
</sequence>
</complexType>
簡化的驗證和擴充代碼:
Schema schema = schemaFactory.newSchema(schemaFile);
Validator validator = schema.newValidator();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new File(xmlFile));
DOMSource input = new DOMSource(document);
DOMResult output = new DOMResult();
validator.validate(input, output);
Document result = (Document)output.getNode();
因此,除了根據模式驗證xml之外,它還應該對其進行擴充並添加任何缺失的默認值(例如sub1),並將其發送到output
。
但是,當xml中缺少sub1
時, result
中將不存在sub1
。
我在哪里走不開?
編輯:
好的,找到了缺少sub1
的原因 。 但是,即使sub1
不在xml中,我如何確保result
也存在sub1
?
該答案引用了規范:擴充將默認值應用於空元素。 它不會添加xml中不存在的元素。
換句話說,通過方案擴充不能保證存在元素。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.