本文整理匯總了C#中System.Xml.XmlValidatingReader.Read方法的典型用法代碼示例。如果您正苦於以下問題:C# XmlValidatingReader.Read方法的具體用法?C# XmlValidatingReader.Read怎麽用?C# XmlValidatingReader.Read使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類System.Xml.XmlValidatingReader
的用法示例。
在下文中一共展示了XmlValidatingReader.Read方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。
示例1: TestSimpleValidation
public void TestSimpleValidation ()
{
string xml = "<root/>";
xvr = PrepareXmlReader (xml);
Assert.AreEqual (ValidationType.Auto, xvr.ValidationType);
XmlSchema schema = new XmlSchema ();
XmlSchemaElement elem = new XmlSchemaElement ();
elem.Name = "root";
schema.Items.Add (elem);
xvr.Schemas.Add (schema);
xvr.Read (); // root
Assert.AreEqual (ValidationType.Auto, xvr.ValidationType);
xvr.Read (); // EOF
xml = "<hoge/>";
xvr = PrepareXmlReader (xml);
xvr.Schemas.Add (schema);
try {
xvr.Read ();
Assert.Fail ("element mismatch is incorrectly allowed");
} catch (XmlSchemaException) {
}
xml = "<hoge xmlns='urn:foo' />";
xvr = PrepareXmlReader (xml);
xvr.Schemas.Add (schema);
try {
xvr.Read ();
Assert.Fail ("Element in different namespace is incorrectly allowed.");
} catch (XmlSchemaException) {
}
}
示例2: Page_Load
protected void Page_Load(object sender, EventArgs e)
{
string xmlFile = Server.MapPath("~/Customers1.xml");
string xsdFile = Server.MapPath("~/Customers.xsd");
XmlTextReader textReader = new XmlTextReader(xmlFile);
XmlValidatingReader validatingReader = new XmlValidatingReader(textReader);
validatingReader.Schemas.Add(null, xsdFile);
validatingReader.ValidationType = ValidationType.Schema;
validatingReader.ValidationEventHandler += new ValidationEventHandler(validatingReader_ValidationEventHandler);
while (validatingReader.Read())
{
if (validatingReader.NodeType == XmlNodeType.Element)
{
if (validatingReader.SchemaType is XmlSchemaComplexType)
{
XmlSchemaComplexType complexType = (XmlSchemaComplexType)validatingReader.SchemaType;
Response.Write(validatingReader.Name + " " + complexType.Name);
}
else
{
object innerText = validatingReader.ReadTypedValue();
Response.Write(validatingReader.Name + " : " + innerText.ToString() + " <br />");
}
}
}
validatingReader.Close();
}
示例3: IsValidXML
/// <summary>
/// Validate XML Format
/// </summary>
/// <param name="text">XML string</param>
public static bool IsValidXML(string text)
{
bool errored;
byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(text);
MemoryStream stream = new MemoryStream(byteArray);
XmlTextReader xmlr = new XmlTextReader(stream);
XmlValidatingReader reader = new XmlValidatingReader(xmlr);
try
{
while (reader.Read()) { ; }
errored = false;
}
catch
{
errored = true;
}
finally
{
reader.Close();
}
return !errored;
}
示例4: ValidaSchema
/// <summary>
/// Valida se um Xml está seguindo de acordo um Schema
/// </summary>
/// <param name="arquivoXml">Arquivo Xml</param>
/// <param name="arquivoSchema">Arquivo de Schema</param>
/// <returns>True se estiver certo, Erro se estiver errado</returns>
public void ValidaSchema(String arquivoXml, String arquivoSchema)
{
//Seleciona o arquivo de schema de acordo com o schema informado
//arquivoSchema = Bll.Util.ContentFolderSchemaValidacao + "\\" + arquivoSchema;
//Verifica se o arquivo de XML foi encontrado.
if (!File.Exists(arquivoXml))
throw new Exception("Arquivo de XML informado: \"" + arquivoXml + "\" não encontrado.");
//Verifica se o arquivo de schema foi encontrado.
if (!File.Exists(arquivoSchema))
throw new Exception("Arquivo de schema: \"" + arquivoSchema + "\" não encontrado.");
// Cria um novo XMLValidatingReader
var reader = new XmlValidatingReader(new XmlTextReader(new StreamReader(arquivoXml)));
// Cria um schemacollection
var schemaCollection = new XmlSchemaCollection();
//Adiciona o XSD e o namespace
schemaCollection.Add("http://www.portalfiscal.inf.br/nfe", arquivoSchema);
// Adiciona o schema ao ValidatingReader
reader.Schemas.Add(schemaCollection);
//Evento que retorna a mensagem de validacao
reader.ValidationEventHandler += Reader_ValidationEventHandler;
//Percorre o XML
while (reader.Read())
{
}
reader.Close(); //Fecha o arquivo.
//O Resultado é preenchido no reader_ValidationEventHandler
if (validarResultado != "")
{
throw new Exception(validarResultado);
}
}
示例5: ParseItemsConfiguration
public static T_SeamateItems ParseItemsConfiguration(String configPath)
{
TextReader tr = null;
XmlTextReader xml = null;
XmlValidatingReader validate = null;
xml = new XmlTextReader(configPath);
validate = new XmlValidatingReader(xml);
validate.ValidationEventHandler += new ValidationEventHandler(xsdValidationHandler);
while (validate.Read()) { }
validate.Close();
try
{
tr = new StreamReader(configPath);
XmlSerializer serializer = new XmlSerializer(typeof(T_SeamateItems));
T_SeamateItems config = (T_SeamateItems)serializer.Deserialize(tr);
tr.Close();
return config;
}
catch (Exception ex)
{
if (tr != null)
{
tr.Close();
}
throw new Exception("Unable to read configuration file: " + configPath, ex);
}
return null;
}
示例6: Main
static void Main (string [] args)
{
string schemaFile = "bug.xsd";
XmlTextReader treader = new XmlTextReader (schemaFile);
XmlSchema sc = XmlSchema.Read (treader, null);
sc.Compile (null);
string page =
"<body xmlns=\"" + sc.TargetNamespace + "\">"
+ "<div>"
+ "</div>"
+ "</body>";
System.Xml.XmlTextReader reader = new XmlTextReader (new StringReader (page));
try {
XmlValidatingReader validator = new System.Xml.XmlValidatingReader (reader);
validator.Schemas.Add (sc);
validator.ValidationType = ValidationType.Schema;
validator.EntityHandling = EntityHandling.ExpandCharEntities;
while (validator.Read ()) {
}
} finally {
reader.Close ();
}
}
示例7: ValidateSchema
public static void ValidateSchema(string xml)
{
var schemaStream = typeof(HoptoadValidator).Assembly.GetManifestResourceStream("Tests.hoptoad_2_0.xsd");
var schema = XmlSchema.Read(schemaStream, (sender, args) => { });
var reader = new StringReader(xml);
var xmlReader = new XmlTextReader(reader);
#pragma warning disable 0618
var validator = new XmlValidatingReader(xmlReader);
#pragma warning restore 0618
var errorBuffer = new StringBuilder();
validator.ValidationEventHandler += (sender, args) => {
errorBuffer.AppendLine(args.Message);
};
validator.Schemas.Add(schema);
while (validator.Read())
{
}
if (errorBuffer.ToString().Length > 0)
Assert.Fail(errorBuffer.ToString());
}
示例8: Validar
/*Validar archivo XML Contra Esquema XSD*/
public void Validar(string rutaFicheroXml)
{
var r = new XmlTextReader(rutaFicheroXml);
var v = new XmlValidatingReader(r) {ValidationType = ValidationType.Schema};
v.ValidationEventHandler += ValidarControlEventos;
var procesarXml = new ConvertirXmlEnTexo();
procesarXml.ProcesarArchivo(rutaFicheroXml/*,@"D:\pruebas.txt"*/);
try
{
while (v.Read())
{
}
// Comprobar si el documento es válido o no.
//return _isValid ? "true" : "false";
// var procesarXml = new ConvertirXmlEnTexo();
// procesarXml.ProcesarArchivo(rutaFicheroXml/*,@"D:\pruebas.txt"*/);
v.Close();
}
catch (Exception e)
{
//ValidarControlEventos(null, null);
// _isValid = false;
// MessageBox.Show("Evento de validación\r\n" + e.Message, @"Validacion de XML",
// MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
////v.ValidationEventHandler += new ValidationEventHandler(ValidarControlEventos);
//return "true";
}
}
示例9: TestEmptySchema
public void TestEmptySchema ()
{
string xml = "<root/>";
xvr = PrepareXmlReader (xml);
xvr.ValidationType = ValidationType.Schema;
xvr.Read (); // Is is missing schema component.
}
示例10: ShouldGenerateASchemaToValidateTestSubClassXml
public void ShouldGenerateASchemaToValidateTestSubClassXml()
{
NetReflectorTypeTable table = new NetReflectorTypeTable
{
typeof (TestClass),
typeof (TestInnerClass),
typeof (TestSubClass)
};
XsdGenerator generator = new XsdGenerator(table);
XmlSchema schema = generator.Generate(true);
#if DEBUG
schema.Write(Console.Out);
#endif
string xmlToValidate = TestClass.GetXmlWithSubClass(DateTime.Today);
#if DEBUG
Console.Out.WriteLine("xmlToValidate = {0}", xmlToValidate);
#endif
XmlValidatingReader reader = new XmlValidatingReader(new XmlTextReader(new StringReader(xmlToValidate)));
reader.Schemas.Add(schema);
reader.ValidationType = ValidationType.Schema;
while (reader.Read()) {}
}
示例11: BaseCodeGenerator
public BaseCodeGenerator(Stream sourceXML)
{
XmlDocument doc = new XmlDocument();
using (sourceXML)
{
doc.Load(sourceXML);
}
MemoryStream ms = new MemoryStream();
doc.Save(ms);
ms.Position = 0;
using (XmlTextReader r = new XmlTextReader(ms))
{
XmlValidatingReader v = new XmlValidatingReader(r);
v.ValidationType = ValidationType.Schema;
v.ValidationEventHandler += new ValidationEventHandler(v_ValidationEventHandler);
while (v.Read())
{
}
v.Close();
}
if (m_errors)
throw new InvalidDataException("The Xml input did not match the schema");
Parse(doc);
}
示例12: Validate
public static void Validate(XmlReader reader)
{
XmlValidatingReader vr = new XmlValidatingReader(reader);
vr.ValidationType = ValidationType.Auto;
vr.ValidationEventHandler += new ValidationEventHandler(ValidationHandler);
while (vr.Read()){};
}
示例13: Main
static void Main(string[] args)
{
if (args.Length != 4)
{
Console.WriteLine("Invalid parameter count. Exiting...");
return;
}
string xmlFile = args[0];
string xdsFile = args[1];
string xdsNamespace = args[2];
string outputFile = args[3];
try
{
XmlSchemaCollection cache = new XmlSchemaCollection();
cache.Add(xdsNamespace, xdsFile);
XmlTextReader r = new XmlTextReader(xmlFile);
XmlValidatingReader v = new XmlValidatingReader(r);
v.Schemas.Add(cache);
v.ValidationType = ValidationType.Schema;
v.ValidationEventHandler +=
new ValidationEventHandler(MyValidationEventHandler);
while (v.Read()) { } // look for validation errors
v.Close();
}
catch (Exception e)
{
encounteredFatalError = true;
fatalError = e;
}
StreamWriter file = new StreamWriter(outputFile);
if (isValid && !encounteredFatalError)
file.WriteLine("PASSED: Document is valid");
else
file.WriteLine("FAILED: Document is invalid");
// Printing
foreach (string entry in list)
{
file.WriteLine(entry);
}
if (encounteredFatalError)
{
file.WriteLine("Error: a FATAL error has occured " +
"while reading the file.\r\n" + fatalError.ToString());
}
file.Close();
}
示例14: Main
static void Main(string[] args)
{
XmlTextReader r = new XmlTextReader(@"..\..\XMLFile1.xml");
XmlValidatingReader v = new XmlValidatingReader(r);
v.ValidationType = ValidationType.Schema;
v.ValidationEventHandler +=
new ValidationEventHandler(MyValidationEventHandler);
while(v.Read())
{
// Can add code here to process the content.
}
v.Close();
// Check whether the document is valid or invalid.
if(m_isValid)
{
Console.WriteLine("Document is valid");
}
else
{
Console.WriteLine("Document is invalid");
}
/*
XmlTextWriter xtw = new XmlTextWriter(new StreamWriter("test1.xml"));
xtw.WriteStartDocument(true);
xtw.WriteStartElement("MapVals");
xtw.WriteStartElement("MapValKey1");
xtw.WriteAttributeString("val1","a");
xtw.WriteAttributeString("val2","b");
xtw.WriteEndElement();
xtw.WriteStartElement("MapValKey2");
xtw.WriteAttributeString("val1","qf");
xtw.WriteAttributeString("val2","xt");
xtw.WriteEndElement();
xtw.WriteStartElement("MapValKey3");
xtw.WriteAttributeString("val1","wwu");
xtw.WriteAttributeString("val2","verble");
xtw.WriteEndElement();
xtw.WriteEndElement();
xtw.WriteEndDocument();
xtw.Close();
*/
}
示例15: Page_Load
private void Page_Load(object sender, System.EventArgs e)
{
XmlValidatingReader reader = null;
XmlSchemaCollection myschema = new XmlSchemaCollection();
ValidationEventHandler eventHandler = new ValidationEventHandler(ShowCompileErrors );
try
{
String xmlFrag = @"<?xml version='1.0' ?>
<item>
<xxx:price xmlns:xxx='xxx' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
xsi:schemaLocation='test.xsd'></xxx:price>
</item>";
/*"<author xmlns='urn:bookstore-schema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>" +
"<first-name>Herman</first-name>" +
"<last-name>Melville</last-name>" +
"</author>";*/
string xsd = @"<?xml version='1.0' encoding='UTF-8'?>
<xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema' targetNamespace='xxx'>
<xsd:element name='price' type='xsd:integer' xsd:default='12'/>
</xsd:schema>";
//Create the XmlParserContext.
XmlParserContext context = new XmlParserContext(null, null, "", XmlSpace.None);
//Implement the reader.
reader = new XmlValidatingReader(xmlFrag, XmlNodeType.Element, context);
//Add the schema.
myschema.Add("xxx", new XmlTextReader(new StringReader(xsd)));
//Set the schema type and add the schema to the reader.
reader.ValidationType = ValidationType.Schema;
reader.Schemas.Add(myschema);
while (reader.Read()){Response.Write(reader.Value);}
Response.Write("<br>Completed validating xmlfragment<br>");
}
catch (XmlException XmlExp)
{
Response.Write(XmlExp.Message + "<br>");
}
catch(XmlSchemaException XmlSchExp)
{
Response.Write(XmlSchExp.Message + "<br>");
}
catch(Exception GenExp)
{
Response.Write(GenExp.Message + "<br>");
}
finally
{}
XmlDocument doc;
}