我通过 Web 服务以字符串格式获取 xml 并通过 xmlreader,我将字符串转换为流对象。但无法弄清楚我错过了什么。这里提到的 xml 和 schema 是一个示例。
class Program
{
static void Main(string[] args)
{
try
{
XmlDocument doc = new XmlDocument();
doc.Load("books.xml");
StringWriter sw = new StringWriter();
XmlTextWriter tx = new XmlTextWriter(sw);
doc.WriteTo(tx);
string leadxml = sw.ToString();
XmlReaderSettings xmlSettings = new XmlReaderSettings();
xmlSettings.Schemas = new System.Xml.Schema.XmlSchemaSet();
xmlSettings.Schemas.Add(string.Empty,"books.xsd");
xmlSettings.ValidationType = ValidationType.Schema;
byte[] byteArray = Encoding.ASCII.GetBytes(leadxml);
MemoryStream stream = new MemoryStream(byteArray);
XmlReader reader = XmlReader.Create(stream, xmlSettings);
// Parse the file.
while (reader.Read());
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
xml 是:
<?xml version="1.0" encoding="utf-8" ?>
<bookstore>
<book genre="autobiography" publicationdate="1981-03-22" ISBN="1-861003-11-0"/>
</bookstore>
xsd 是:
<?xml version="1.0" encoding="utf-8"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="bookstore">
<xs:complexType>
<xs:sequence>
<xs:element maxOccurs="unbounded" name="book">
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>