本文整理匯總了C#中System.Xml.XmlValidatingReader.Close方法的典型用法代碼示例。如果您正苦於以下問題:C# XmlValidatingReader.Close方法的具體用法?C# XmlValidatingReader.Close怎麽用?C# XmlValidatingReader.Close使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類System.Xml.XmlValidatingReader
的用法示例。
在下文中一共展示了XmlValidatingReader.Close方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。
示例1: 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);
}
示例2: 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);
}
}
示例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: Read
public static WebReferenceOptions Read(XmlReader xmlReader, ValidationEventHandler validationEventHandler)
{
WebReferenceOptions options;
XmlValidatingReader reader = new XmlValidatingReader(xmlReader) {
ValidationType = ValidationType.Schema
};
if (validationEventHandler != null)
{
reader.ValidationEventHandler += validationEventHandler;
}
else
{
reader.ValidationEventHandler += new ValidationEventHandler(WebReferenceOptions.SchemaValidationHandler);
}
reader.Schemas.Add(Schema);
webReferenceOptionsSerializer serializer = new webReferenceOptionsSerializer();
try
{
options = (WebReferenceOptions) serializer.Deserialize(reader);
}
catch (Exception exception)
{
throw exception;
}
finally
{
reader.Close();
}
return options;
}
示例5: GReader
public GReader(string path)
{
document = new XmlDocument ();
try {
XmlTextReader textreader = new XmlTextReader (path);
XmlValidatingReader vreader = new XmlValidatingReader (textreader);
// Set the validation event handler
vreader.ValidationEventHandler += new ValidationEventHandler (ValidationCallBack);
// Load the XML to Document node.
document.Load (textreader);
Console.WriteLine ("Validation finished. Validation {0}", (m_success==true ? "successful!" : "failed."));
//Close the reader.
vreader.Close();
} catch (FileNotFoundException e) {
Console.WriteLine ("Error: {0} not found.", e.FileName);
Environment.Exit (1);
} catch (DirectoryNotFoundException) {
Console.WriteLine ("Error: {0} not found.", path);
Environment.Exit (1);
} catch (XmlException) {
Console.WriteLine ("Error: {0} is not well-formed xml.", path);
Environment.Exit (1);
}
}
示例6: 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;
}
示例7: 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();
}
示例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: 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();
}
示例10: 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();
*/
}
示例11: Read
/// <summary>
///
/// </summary>
///
/// <param name="directory"></param>
/// <param name="ruleName"></param>
///
/// <returns></returns>
///
public static List<RuleItem> Read(string directory, string ruleName)
{
List<RuleItem> result = new List<RuleItem>();
foreach (string file in Directory.GetFiles(directory, "*.xml"))
{
XmlValidatingReader reader = null;
try
{
XmlDocument xml = new XmlDocument();
reader = new XmlValidatingReader(new XmlTextReader(file));
reader.ValidationType = ValidationType.None;
xml.Load(reader);
reader.Close();
XmlElement rootNode = (XmlElement) xml.SelectSingleNode("/applicationlogic");
XmlNodeList ruleNodes = rootNode.SelectNodes(ruleName);
// extract each rule.
foreach (XmlElement ruleSource in ruleNodes)
{
RuleItem rule = new RuleItem(ruleName, xml, ruleSource, directory, file);
result.Add(rule);
}
}
catch (Exception exception)
{
log.Warn(string.Format("Failed to read rules file: {0}.", file), exception);
}
finally
{
if (reader != null && reader.ReadState != ReadState.Closed)
{
reader.Close();
}
}
}
return result;
}
示例12: XPathDocument
public XPathDocument (string uri, XmlSpace space)
{
XmlValidatingReader vr = null;
try {
vr = new XmlValidatingReader (new XmlTextReader (uri));
vr.ValidationType = ValidationType.None;
Initialize (vr, space);
} finally {
if (vr != null)
vr.Close ();
}
}
示例13: Validate
public void Validate(string strXMLDoc)
{
try
{
// Declare local objects
XmlTextReader tr = null;
XmlSchemaCollection xsc = null;
XmlValidatingReader vr = null;
// Text reader object
tr = new XmlTextReader(Application.StartupPath + @"\BDOCImportSchema.xsd");
xsc = new XmlSchemaCollection();
xsc.Add(null, tr);
// XML validator object
vr = new XmlValidatingReader(strXMLDoc,
XmlNodeType.Document, null);
vr.Schemas.Add(xsc);
// Add validation event handler
vr.ValidationType = ValidationType.Schema;
vr.ValidationEventHandler +=
new ValidationEventHandler(ValidationHandler);
// Validate XML data
while (vr.Read()) ;
vr.Close();
// Raise exception, if XML validation fails
if (ErrorsCount > 0)
{
throw new Exception(ErrorMessage);
}
// XML Validation succeeded
Console.WriteLine("XML validation succeeded.\r\n");
}
catch (Exception error)
{
// XML Validation failed
Console.WriteLine("XML validation failed." + "\r\n" +
"Error Message: " + error.Message);
throw new Exception("Error in XSD verification:\r\n" + error.Message);
}
}
示例14: Render
private void Render(Stream stream, string xslResourceId, string xslResourceDefault, XsltArgumentList args) {
XslTransform xslt = new XslTransform();
xslt.Load(new XmlTextReader(Assembly
.GetExecutingAssembly()
.GetManifestResourceStream(Parameter.GetString(xslResourceId, xslResourceDefault))),
null,
null);
XmlValidatingReader reader = new XmlValidatingReader(new XmlTextReader(ruleFileURI));
reader.ValidationType = ValidationType.Schema;
reader.Schemas.Add(XmlSchema.Read(Assembly
.GetExecutingAssembly()
.GetManifestResourceStream(Parameter.GetString("xbusinessrules.xsd", "resource.xBusinessRules.xsd")),
null));
xslt.Transform(new XPathDocument(reader), args, stream, null);
reader.Close();
}
示例15: ValidateFile
static void ValidateFile (string file)
{
IsValid = true;
try {
reader = new XmlValidatingReader (new XmlTextReader (file));
reader.ValidationType = ValidationType.Schema;
reader.Schemas.Add (schema);
reader.ValidationEventHandler += new ValidationEventHandler (OnValidationEvent);
while (reader.Read ()) {
// do nothing
}
reader.Close ();
}
catch (Exception e) {
Console.WriteLine ("mdvalidator: error: " + e.ToString ());
}
}