[英]Validating XML against XSD when XSD changes
Lets suppose I have an XSD
schema named xsd1
. 假设我有一个名为
xsd1
的XSD
模式。 Assume that a generated class looks like 假设生成的类看起来像
public class ClassA
{
public string Prop1 { get; set; }
public string Prop2 { get; set; }
}
Then I create a new schema xsd2
which is almost the same as xsd1. 然后,我创建一个新的模式
xsd2
这几乎是一样的xsd1。 It has only one more element Prop3
of type int
. 它仅具有一个
int
类型的元素Prop3
。 Then ClassA
changes to 然后,
ClassA
更改为
public class ClassA
{
public string Prop1 { get; set; }
public string Prop2 { get; set; }
public int Prop3 { get; set; }
}
Now, when I serialize an instance of ClassA
to XML, validation against xsd1
fails with message 现在,当我将
ClassA
的实例序列化为XML时,针对xsd1
验证失败,并显示以下消息:
Invalid child element 'Prop3' 无效的子元素“ Prop3”
How can I have both validations succeed? 如何使两个验证都成功? I don't want two separate classes.
我不要两个单独的课。
Serialized object 序列化对象
var a = new ClassA() { Prop1 = "p1", Prop2 = "p2" };
looks like 看起来像
<ClassA>
<Prop1>p1</Prop1>
<Prop2>p2</Prop2>
</ClassA>
when I add Prop3
to ClassA
then the serialized object a
becommes 当我将
Prop3
添加到ClassA
,序列化的对象a
<ClassA>
<Prop1>p1</Prop1>
<Prop2>p2</Prop2>
<Prop3>0</Prop3>
</ClassA>
and as so not valid against schema xsd1
. 因此对于模式
xsd1
。 When validating against xsd1
I want only Prop1
and Prop2
to be serialized. 当对验证
xsd1
我只想Prop1
和Prop2
被序列化。
Your question resembles a schema versioning question where you seek both forward and backward compatibility while adding a new element. 您的问题类似于架构版本问题,在添加新元素的同时寻求向前和向后兼容性。 That is simply not possible.
那根本不可能。
Adding an optional element allows XML that was valid against XSD 1 to continue to be valid with the new version, XSD 2 . 添加可选元素可以使对XSD 1有效的XML在新版本XSD 2中继续有效。 That part is fine.
那部分很好。 However, any XML that includes the optional new element will not be valid against the original version, XSD 1 .
但是,任何包含可选的new元素的XML对原始版本XSD 1均无效。
When I publish a new schema, clients need time to adapt their code.
当我发布新的架构时,客户需要时间来适应他们的代码。
Fair enough -- a common requirement. 足够公平-这是一个共同的要求。
Our clients sends us data (objects, not xml)
我们的客户向我们发送数据(对象,而不是xml)
That's backward from recommended best practices. 这与推荐的最佳做法不符。
they determine against which schema should it be validated
他们确定应针对哪个架构进行验证
Then either honor their commitment (rather than trying to defeat it) by supporting both XSDs during transition, or build in flexibility to your XSDs via liberal mechanisms such as xsd:any
. 然后要么通过在过渡期间支持两个XSD来兑现他们的承诺(而不是试图击败它),要么通过
xsd:any
类的自由机制为XSD增强灵活性。 It's up to you, but you cannot expect validation be both strict and liberal simultaneously. 这取决于您,但是您不能期望同时进行严格和自由验证。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.