【发布时间】:2014-07-07 15:12:56
【问题描述】:
我正在使用 XML Schema 文件来验证传递给 Web 服务的 XML 实例。我想知道是否有可能在 XML 实例中有一些其他可以忽略的标签,或者如果字符串与架构“完全”不匹配,它会失败?
例如:
<?xml version="1.0" encoding="utf-8"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema" >
<xs:element name="DSSData">
<xs:complexType>
<xs:sequence>
<xs:element name="LTSN" type="xs:string" />
<xs:element name="Timestamp" type="xs:string" />
<xs:element name="Stats" maxOccurs="1" minOccurs="0">
<xs:complexType>
<xs:sequence>
<xs:element name="Trp" type="xs:integer" nillable="true" minOccurs="1" />
<xs:element name="Keyed" type="xs:integer" nillable="true" minOccurs="1" />
<xs:element name="Pieces" type="xs:integer" nillable="true" minOccurs="1" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
我传递了以下 XML 字符串:
<DSSData><LTSN>abcd</LTSN><Timestamp></Timestamp><Stats><Trp>12</Trp><Keyed>34</Keyed><Pieces>12</Pieces><Ocr>45</Ocr><OcrNoBC>87</OcrNoBC></Stats></DSSData>
添加了一个新标签<newTag>。
更新:
这是用来验证 XML 的:
bool bIsValid = ValidXMLDoc(my_xml_string, "", "some_schema.xsd");
public bool ValidXmlDoc(string xml, string sSchemaNamespace, string schemaUri)
{
try
{
// Is the xml string valid?
if(xml == null || xml.Length < 1)
{
return false;
}
StringReader srXml = new StringReader(xml);
return ValidXmlDoc(srXml, sSchemaNamespace, schemaUri);
}
catch(Exception ex)
{
this.ValidationError = ex.Message;
return false;
}
}
public bool ValidXmlDoc(StringReader xml, string schemaNamespace, string schemaUri)
{
// Continue?
if(xml == null || schemaNamespace == null || schemaUri == null)
{
return false;
}
isValidXml = true;
XmlValidatingReader vr;
XmlTextReader tr;
XmlSchemaCollection schemaCol = new XmlSchemaCollection();
schemaCol.Add(schemaNamespace, schemaUri);
try
{
// Read the xml.
tr = new XmlTextReader(xml);
// Create the validator.
vr = new XmlValidatingReader(tr);
// Set the validation tyep.
vr.ValidationType = ValidationType.Schema;
// Add the schema.
if(schemaCol != null)
{
vr.Schemas.Add(schemaCol);
}
// Set the validation event handler.
vr.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);
// Read the xml schema.
while(vr.Read())
{
}
vr.Close();
return isValidXml;
}
catch(Exception ex)
{
this.ValidationError = ex.Message;
return false;
}
finally
{
// Clean up...
vr = null;
tr = null;
}
}
谢谢。
【问题讨论】: