0
javax.xml.validation.Validator有一個method來驗證和增強對模式的xml。使用XML Schema增強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
。
但是,sub1
不存在於result
中,因爲它在xml中缺失。
我在哪裏跟蹤?
編輯:
好了,找到了reason爲什麼sub1
丟失。但是如何確保sub1
在result
中存在,即使它不在xml中?
如果它是可選的,它不存在,那麼爲什麼你需要添加節點? – ChadNC 2012-03-27 14:43:21
請參閱http://stackoverflow.com/questions/9884051/how-to-update-xml-file-from-another-xml-file-dynamically/9884503#9884503 – 2012-03-28 06:11:37
它應該是一個config.xml,每當元素是在xml中缺少,增加的'Document'應該只使用xsd中的默認值,所以代碼不必擔心默認值。 – riha 2012-03-29 08:15:34