使用以下我总是得到一个无效的子元素错误。我是 XML 新手,我一直在网上寻找并试图解决这个问题,但没有运气。我有另一个 XSD 正在验证提交给我的应用程序的 XML,它工作得很好,但它使用的是属性而不是元素。无法使用 XSD 中的元素来验证通过我无法控制的第 3 方应用程序提交的 XML。
XSD
XML
<?xml version="1.0" encoding="Windows-1252"?> <xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="SCCAParticipationList"> <xs:complexType> <xs:sequence> <xs:element maxOccurs="unbounded" name="Entry"> <xs:complexType> <xs:sequence> <xs:element name="Address" type="xs:string" minOccurs="0" /> <xs:element name="CarModel" type="xs:string" minOccurs="0" /> <xs:element name="CarNo" type="xs:string" minOccurs="0" /> <xs:element name="TotalTm" type="xs:string" minOccurs="0" /> <xs:element name="BestTm" type="xs:string" minOccurs="0" /> <xs:element name="Region" type="xs:string" minOccurs="0" /> <xs:element name="MemberNo" type="xs:string" minOccurs="1" /> <xs:element name="FirstName" type="xs:string" minOccurs="1" /> <xs:element name="LastName" type="xs:string" minOccurs="1" /> <xs:element name="Class" type="xs:string" minOccurs="1" /> <xs:element name="Pos" type="xs:string" minOccurs="1" /> <xs:element name="UniqueID" type="xs:string" minOccurs="0" /> </xs:sequence> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:schema>
<?xml version="1.0"?> <SCCAParticipationList> <Entry> <MemberNo>3333333</MemberNo> <FirstName>Test</FirstName> <LastName>Person</LastName> <Class>stt</Class> <Pos>13</Pos> <CarModel>Mazda Miata</CarModel> <Address>123 Test Dr ,The Woodlands TX,55555,US</Address> </Entry> <Entry> <MemberNo>2222222</MemberNo> <FirstName>John</FirstName> <LastName>Doe</LastName> <Class>sio</Class> <Pos>3T</Pos> <CarModel>Subaru Impreza</CarModel> <Address>111 Test Circle ,Austin TX,77777,US</Address> </Entry> </SCCAParticipationList>
C#
protected Boolean VerifyXmlwElements(string strSchemaPath, string strXml) { try {
byte[] byteArray = Encoding.ASCII.GetBytes(strXml); MemoryStream stream = new MemoryStream(byteArray); XmlTextReader xmlr = new XmlTextReader(stream); XmlValidatingReader xmlvread = new XmlValidatingReader(xmlr); xmlvread.Schemas.Add(null, strSchemaPath);xmlvread.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack); while (xmlvread.Read()) { } xmlvread.Close(); if (intErrCount > 0) { intErrCount--; throw new Exception(strErrMessage); } strErrMessage = "XML validation succeeded!\r\n"; return true; } catch (Exception ex) { intErrCount++; strErrMessage = "Invalid XML - " + ex.Message + intErrCount.ToString() + " Error(s)\r\n"; return false; } } private void ValidationCallBack(Object sender, ValidationEventArgs args) { if (args.Message.ToLower().Contains("attribute is not declared")) { return; } intErrCount++; return; }