本文整理匯總了C#中System.Xml.Schema.XmlSchemaCollection.Add方法的典型用法代碼示例。如果您正苦於以下問題:C# XmlSchemaCollection.Add方法的具體用法?C# XmlSchemaCollection.Add怎麽用?C# XmlSchemaCollection.Add使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類System.Xml.Schema.XmlSchemaCollection
的用法示例。
在下文中一共展示了XmlSchemaCollection.Add方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。
示例1: TestAdd
public void TestAdd ()
{
XmlSchemaCollection col = new XmlSchemaCollection ();
XmlSchema schema = new XmlSchema ();
XmlSchemaElement elem = new XmlSchemaElement ();
elem.Name = "foo";
schema.Items.Add (elem);
schema.TargetNamespace = "urn:foo";
col.Add (schema);
col.Add (schema); // No problem !?
XmlSchema schema2 = new XmlSchema ();
schema2.Items.Add (elem);
schema2.TargetNamespace = "urn:foo";
col.Add (schema2); // No problem !!
schema.Compile (null);
col.Add (schema);
col.Add (schema); // Still no problem !!!
schema2.Compile (null);
col.Add (schema2);
schema = GetSchema ("Test/XmlFiles/xsd/3.xsd");
schema.Compile (null);
col.Add (schema);
schema2 = GetSchema ("Test/XmlFiles/xsd/3.xsd");
schema2.Compile (null);
col.Add (schema2);
}
示例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: TestAddDoesCompilation
public void TestAddDoesCompilation ()
{
XmlSchema schema = new XmlSchema ();
Assert (!schema.IsCompiled);
XmlSchemaCollection col = new XmlSchemaCollection ();
col.Add (schema);
Assert (schema.IsCompiled);
}
示例4: clsSValidator
public clsSValidator(string sXMLFileName, string sSchemaFileName)
{
m_sXMLFileName = sXMLFileName;
m_sSchemaFileName = sSchemaFileName;
m_objXmlSchemaCollection = new XmlSchemaCollection ();
//adding the schema file to the newly created schema collection
m_objXmlSchemaCollection.Add (null, m_sSchemaFileName);
}
示例5: ParseString
public NSTScorePartwise ParseString(string dataString)
{
//todo: parse string
IList<NSTPart> partList = new List<NSTPart>();
XmlTextReader textReader = new XmlTextReader(new FileStream("C:\\NM\\ScoreTranscription\\NETScoreTranscription\\NETScoreTranscriptionLibrary\\OtherDocs\\musicXML.xsd", System.IO.FileMode.Open)); //todo: pass stream in instead of absolute location for unit testing
XmlSchemaCollection schemaCollection = new XmlSchemaCollection();
schemaCollection.Add(null, textReader);
NSTScorePartwise score;
using (XmlValidatingReader reader = new XmlValidatingReader(XmlReader.Create(new StringReader(dataString), new XmlReaderSettings() { DtdProcessing = DtdProcessing.Parse }))) //todo: make unobsolete
{
reader.Schemas.Add(schemaCollection);
reader.ValidationType = ValidationType.Schema;
reader.ValidationEventHandler += new System.Xml.Schema.ValidationEventHandler(ValidationEventHandler);
XmlSerializer serializer = new XmlSerializer(typeof(NSTScorePartwise), new XmlRootAttribute("score-partwise"));
score = (NSTScorePartwise)serializer.Deserialize(reader);
/*
while (reader.Read())
{
if (reader.IsEmptyElement)
throw new Exception(reader.Value); //todo: test
switch (reader.NodeType)
{
case XmlNodeType.Element:
switch (reader.Name.ToLower())
{
case "part-list":
break;
case "score-partwise":
break;
case "part-name":
throw new Exception("pn");
break;
}
break;
case XmlNodeType.Text:
break;
case XmlNodeType.XmlDeclaration:
case XmlNodeType.ProcessingInstruction:
break;
case XmlNodeType.Comment:
break;
case XmlNodeType.EndElement:
break;
}
}*/
}
return score;
}
示例6: 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();
}
示例7: 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;
}
示例8: v2
//[Variation(Desc = "v2 - Contains with not added schema")]
public void v2()
{
XmlSchemaSet sc = new XmlSchemaSet();
#pragma warning disable 0618
XmlSchemaCollection scl = new XmlSchemaCollection();
#pragma warning restore 0618
XmlSchema Schema = scl.Add(null, TestData._XsdAuthor);
Assert.Equal(sc.Contains(Schema), false);
return;
}
示例9: 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);
}
}
示例10: ValidateXml
public static void ValidateXml(Stream xmlStream, XmlSchema xsdSchema)
{
XmlTextReader reader1 = null;
try
{
reader1 = new XmlTextReader(xmlStream);
XmlSchemaCollection collection1 = new XmlSchemaCollection();
collection1.Add(xsdSchema);
XmlValidatingReader reader2 = new XmlValidatingReader(reader1);
reader2.ValidationType = ValidationType.Schema;
reader2.Schemas.Add(collection1);
ArrayList list1 = new ArrayList();
while (reader2.ReadState != ReadState.EndOfFile)
{
try
{
reader2.Read();
continue;
}
catch (XmlSchemaException exception1)
{
list1.Add(exception1);
continue;
}
}
if (list1.Count != 0)
{
throw new XmlValidationException(list1);
}
}
catch (XmlValidationException exception2)
{
throw exception2;
}
catch (Exception exception3)
{
throw new XmlValidationException(exception3.Message, exception3);
}
finally
{
if (reader1 != null)
{
reader1.Close();
}
}
}
示例11: SchemaValidator
public SchemaValidator(string xmlFile, string schemaFile)
{
XmlSchemaCollection myXmlSchemaCollection = new XmlSchemaCollection();
XmlTextReader xmlTextReader = new XmlTextReader(schemaFile);
try
{
myXmlSchemaCollection.Add(XmlSchema.Read(xmlTextReader, null));
}
finally
{
xmlTextReader.Close();
}
// Validate the XML file with the schema
XmlTextReader myXmlTextReader = new XmlTextReader (xmlFile);
myXmlValidatingReader = new XmlValidatingReader(myXmlTextReader);
myXmlValidatingReader.Schemas.Add(myXmlSchemaCollection);
myXmlValidatingReader.ValidationType = ValidationType.Schema;
}
示例12: PcaCompiler
public PcaCompiler()
{
try
{
Assembly assembly = Assembly.GetExecutingAssembly();
// read schema
using (Stream s = assembly.GetManifestResourceStream("Microsoft.Tools.WindowsInstallerXml.Xsd.pubca.xsd"))
{
this.xmlSchema = XmlSchema.Read(s, null);
}
// read table definitions
using (Stream s = assembly.GetManifestResourceStream("Microsoft.Tools.WindowsInstallerXml.Data.tables.xml"))
{
XmlReader tableDefinitionsReader = new XmlTextReader(s);
#if DEBUG
Assembly wixAssembly = Assembly.GetAssembly(typeof(Compiler));
using (Stream schemaStream = wixAssembly.GetManifestResourceStream("Microsoft.Tools.WindowsInstallerXml.Xsd.tables.xsd"))
{
XmlReader schemaReader = new XmlTextReader(schemaStream);
XmlSchemaCollection schemas = new XmlSchemaCollection();
schemas.Add("http://schemas.microsoft.com/wix/2003/04/tables", schemaReader);
XmlValidatingReader validatingReader = new XmlValidatingReader(tableDefinitionsReader);
validatingReader.Schemas.Add(schemas);
tableDefinitionsReader = validatingReader;
}
#endif
this.tableDefinitionCollection = TableDefinitionCollection.Load(tableDefinitionsReader);
tableDefinitionsReader.Close();
}
}
catch (Exception e)
{
Debug.WriteLine(e.ToString());
System.Console.WriteLine(e.ToString());
throw;
}
}
示例13: NfeDadosMgs
private void NfeDadosMgs()
{
StreamReader ler = null; ;
XmlSchemaCollection myschema = new XmlSchemaCollection();
XmlValidatingReader reader;
string _ano = DateTime.Now.ToString("yy");
_id = _cuf + _ano + _cnpj + _mod + _serie + _nnfini + _nnffim;
try
{
XDocument xDados = new XDocument(new XElement(pf + "inutNFe", new XAttribute("versao", _pversaoaplic),
new XElement(pf + "infInut", new XAttribute("Id", "ID" + _id),
new XElement(pf + "tpAmb", _tpamp),
new XElement(pf + "xServ", "INUTILIZAR"),
new XElement(pf + "cUF", _cuf),
new XElement(pf + "ano", DateTime.Now.ToString("yy")),
new XElement(pf + "CNPJ", _cnpj),
new XElement(pf + "mod", _mod),
new XElement(pf + "serie", Convert.ToInt16(_serie)),
new XElement(pf + "nNFIni", Convert.ToInt32(_nnfini)),
new XElement(pf + "nNFFin", Convert.ToInt32(_nnffim)),
new XElement(pf + "xJust", _sjust))));
xDados.Save(_spath + "\\" + _id + "_ped_inu.xml");
AssinaNFeInutXml assinaInuti = new AssinaNFeInutXml();
assinaInuti.ConfigurarArquivo(_spath + "\\" + _id + "_ped_inu.xml", "infInut", cert);
ler = File.OpenText(_spath + "\\" + _id + "_ped_inu.xml");
XmlParserContext context = new XmlParserContext(null, null, "", XmlSpace.None);
reader = new XmlValidatingReader(ler.ReadToEnd().ToString(), XmlNodeType.Element, context);
myschema.Add("http://www.portalfiscal.inf.br/nfe", _sschema + "\\inutNFe_v2.00.xsd");
reader.ValidationType = ValidationType.Schema;
reader.Schemas.Add(myschema);
while (reader.Read())
{ }
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
finally
{
ler.Close();
}
}
示例14: GetSchemas
/// <summary>
/// Get the schemas required to validate a library.
/// </summary>
/// <returns>The schemas required to validate a library.</returns>
internal static XmlSchemaCollection GetSchemas()
{
if (null == Localization.schemas)
{
Assembly assembly = Assembly.GetExecutingAssembly();
using (Stream localizationSchemaStream = assembly.GetManifestResourceStream("Microsoft.Tools.WindowsInstallerXml.Xsd.wixloc.xsd"))
{
schemas = new XmlSchemaCollection();
XmlSchema localizationSchema = XmlSchema.Read(localizationSchemaStream, null);
schemas.Add(localizationSchema);
}
}
return schemas;
}
示例15: InitializeTask
/// <summary>
/// Initializes the task and verifies parameters.
/// </summary>
/// <param name="TaskNode">Node that contains the XML fragment used to define this task instance.</param>
protected override void InitializeTask(XmlNode TaskNode)
{
XmlElement taskXml = (XmlElement) TaskNode.Clone();
// Expand all properties in the task and its child elements
if (taskXml.ChildNodes != null) {
ExpandPropertiesInNodes(taskXml.ChildNodes);
if (taskXml.Attributes != null) {
foreach (XmlAttribute attr in taskXml.Attributes) {
attr.Value = Properties.ExpandProperties(attr.Value, Location);
}
}
}
// Get the [SchemaValidator(type)] attribute
SchemaValidatorAttribute[] taskValidators =
(SchemaValidatorAttribute[])GetType().GetCustomAttributes(
typeof(SchemaValidatorAttribute), true);
if (taskValidators.Length > 0) {
SchemaValidatorAttribute taskValidator = taskValidators[0];
XmlSerializer taskSerializer = new XmlSerializer(taskValidator.ValidatorType);
// get embedded schema resource stream
Stream schemaStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(
taskValidator.ValidatorType.Namespace);
// ensure schema resource was embedded
if (schemaStream == null) {
throw new BuildException(string.Format(CultureInfo.InvariantCulture,
"Schema resource '{0}' could not be found.",
taskValidator.ValidatorType.Namespace), Location);
}
// load schema resource
XmlTextReader tr = new XmlTextReader(
schemaStream, XmlNodeType.Element, null);
// Add the schema to a schema collection
XmlSchema schema = XmlSchema.Read(tr, null);
XmlSchemaCollection schemas = new XmlSchemaCollection();
schemas.Add(schema);
string xmlNamespace = (taskValidator.XmlNamespace != null ? taskValidator.XmlNamespace : GetType().FullName);
// Create a namespace manager with the schema's namespace
NameTable nt = new NameTable();
XmlNamespaceManager nsmgr = new XmlNamespaceManager(nt);
nsmgr.AddNamespace(string.Empty, xmlNamespace);
// Create a textreader containing just the Task's Node
XmlParserContext ctx = new XmlParserContext(
null, nsmgr, null, XmlSpace.None);
taskXml.SetAttribute("xmlns", xmlNamespace);
XmlTextReader textReader = new XmlTextReader(taskXml.OuterXml,
XmlNodeType.Element, ctx);
// Copy the node from the TextReader and indent it (for error
// reporting, since NAnt does not retain formatting during a load)
StringWriter stringWriter = new StringWriter();
XmlTextWriter textWriter = new XmlTextWriter(stringWriter);
textWriter.Formatting = Formatting.Indented;
textWriter.WriteNode(textReader, true);
//textWriter.Close();
XmlTextReader formattedTextReader = new XmlTextReader(
stringWriter.ToString(), XmlNodeType.Document, ctx);
// Validate the Task's XML against its schema
XmlValidatingReader validatingReader = new XmlValidatingReader(
formattedTextReader);
validatingReader.ValidationType = ValidationType.Schema;
validatingReader.Schemas.Add(schemas);
validatingReader.ValidationEventHandler +=
new ValidationEventHandler(Task_OnSchemaValidate);
while (validatingReader.Read()) {
// Read strictly for validation purposes
}
validatingReader.Close();
if (!_validated) {
// Log any validation errors that have ocurred
for (int i = 0; i < _validationExceptions.Count; i++) {
BuildException ve = (BuildException) _validationExceptions[i];
if (i == _validationExceptions.Count - 1) {
// If this is the last validation error, throw it
throw ve;
}
Log(Level.Info, ve.Message);
}
}
NameTable taskNameTable = new NameTable();
XmlNamespaceManager taskNSMgr = new XmlNamespaceManager(taskNameTable);
//.........這裏部分代碼省略.........