gpt4 book ai didi

xml - 通过 JAXB 验证 XML

转载 作者:行者123 更新时间:2023-12-04 00:34:26 24 4
gpt4 key购买 nike

如果一个 XML 文件被 JAXB 正确解码,我们可以说它是有效的吗? (因为我们正在正确获取 POJO 对象)

最佳答案

如果 Unmarshalled 工作正常,则 XML 格式正确,但如果您有架构,则可以添加 XSD 验证。

下面是架构验证示例。

  JAXBContext jaxbContext = JAXBContext.newInstance(new Class[]{Root.class});
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

//Source yourSchema.xsd
InputStream xsdStream = CopyMetaInfos.class.getClassLoader().getResourceAsStream(SCHEMA);
StreamSource xsdSource = new StreamSource(xsdStream);

Schema schema = schemaFactory.newSchema(new StreamSource[]{xsdSource});

Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
unmarshaller.setSchema(schema);
Root root = (Root) unmarshaller.unmarshal(is);

此验证检查 XML 是否遵循架构的约束。

例如(这个元素必须是 0 <= x <= 10)

<xs:element name="age">
<xs:simpleType>
<xs:restriction base="xs:integer">
<xs:minInclusive value="0"/>
<xs:maxInclusive value="100"/>
</xs:restriction>
</xs:simpleType>
</xs:element>

例如(这个元素必须是强制性的)

<xs:element name="child_name" type="xs:string" minOccurs="1"/>

关于xml - 通过 JAXB 验证 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26174496/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com