我遇到了针对由svcutil生成的架构验证xml文件的问题。出于此问题的目的,请参阅下面的代码片段,其中包含仅简化的XSD架构和我尝试验证的XML文档:
Imports System.Xml.Schema
Module Main
Dim errors As Boolean = False
Sub Main()
Try
Dim xsdMarkup As XElement = _
<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' xmlns:tns="http://zen/myservices" targetNamespace="http://zen/myservices">
<xs:element name="Car" type="tns:CarType"/>
<xs:complexType name="CarType">
<xs:sequence>
<xs:element name="Make" minOccurs="1" maxOccurs="1"/>
<xs:element name="Model" minOccurs="1" maxOccurs="1"/>
</xs:sequence>
</xs:complexType>
</xs:schema>
Dim schemas As XmlSchemaSet = New XmlSchemaSet()
schemas.Add("http://zen/myservices", xsdMarkup.CreateReader)
Dim doc1 As XDocument = _
<?xml version='1.0'?>
<Car>
<Makee>content1</Makee>
<Model>content1</Model>
</Car>
Console.WriteLine("Validating doc1")
errors = False
doc1.Validate(schemas, AddressOf XSDErrors)
Console.WriteLine("doc1 {0}", IIf(errors = True, "did not validate", "validated"))
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
Console.WriteLine("Hit <ENTER> to exit...")
Console.ReadKey()
End Sub
Private Sub XSDErrors(ByVal o As Object, ByVal e As ValidationEventArgs)
Console.WriteLine("{0}", e.Message)
errors = True
End Sub
End Module
此特定情况下的验证应该失败('Make'元素拼写错误)。有趣的是,虽然它通过了。
任何想法我在这段代码中缺少什么?
感谢您的帮助。
禅
答案 0 :(得分:0)
全套。我自己解决了这个问题。我不小心遗漏了正在验证的XML中的名称空间定义:
<?xml version='1.0'?>
<Car>
<Makee>content1</Makee>
<Model>content1</Model>
</Car>
应该是:
<?xml version='1.0'?>
<tns:Car xmlns:tns="http://zen/myservices">
<Makee>content1</Makee>
<Model>content1</Model>
</tns:Car>
验证现在按预期失败。
禅