简体   繁体   English

具有XML模式的增强XML

[英]Augment XML with XML Schema

javax.xml.validation.Validator has a method to validate and augment xml against a schema. javax.xml.validation.Validator具有一种针对模式验证和扩充xml的方法

Simplified xml: 简化的xml:

<something>
  <sub1>false</sub1> <!-- Suppose sub1 is optional and may not be present in xml -->
  <sub2>false</sub2>
</something>

Simplified xsd: 简化的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>

Simplified validation and augmentation code: 简化的验证和扩充代码:

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();

So, besides validating xml against the schema, it should also augment it and add any missing defaults (like sub1) and send that into output . 因此,除了根据模式验证xml之外,它还应该对其进行扩充并添加任何缺失的默认值(例如sub1),并将其发送到output

However, sub1 is not present in result when it is missing in xml. 但是,当xml中缺少sub1时, result中将不存在sub1

Where am I off track here? 我在哪里走不开?

EDIT: 编辑:

Ok, found the reason why sub1 is missing. 好的,找到了缺少sub1原因 But how can I ensure that sub1 is present in result even when it's not in xml? 但是,即使sub1不在xml中,我如何确保result也存在sub1

This answer quotes the spec: augmentation applies default values to empty elements. 答案引用了规范:扩充将默认值应用于空元素。 It does NOT add elements that are not present in xml. 它不会添加xml中不存在的元素。

In other words, augmentation by schema cannot guarantee that elements are present. 换句话说,通过方案扩充不能保证存在元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM