概述
using System;
using System.IO;
using System.Xml;
using System.Xml.Schema;
namespace REIT.ALEIS.Xml
{
/// <summary>
/// ReitXmlDataValidator 从一个xsd文件中查找
/// 某个元素或属性的数据类型,并将它转换为.Net的数据类型
/// </summary>
public class ReitXmlDataTypeFinder
{
private XmlSchema m_Schema;
public ReitXmlDataTypeFinder(string XSDFilePath)
{
FileStream fs;
try
{
fs = new FileStream(XSDFilePath, FileMode.Open);
m_Schema = XmlSchema.Read(fs,new ValidationEventHandler(ShowCompileError));
m_Schema.Compile(new ValidationEventHandler(ShowCompileError));//这里一定要编译一次
}
catch
{
throw;
}
}
public System.Type FindElementType(string ElementName)
{
System.Xml.XmlQualifiedName Name = new XmlQualifiedName(ElementName,@"http://www.reitweb.com/fc");
XmlSchemaObject obj = m_Schema.Elements[Name];
if(obj==null) return null;
return FindType(obj);
}
public System.Type FindAttributeType(string AttributeName)
{
System.Xml.XmlQualifiedName AttrName = new XmlQualifiedName(AttributeName,@"http://www.reitweb.com/fc");
XmlSchemaObject obj = m_Schema.Attributes[AttrName];
if(obj==null) return null;
if (obj.GetType() != typeof(XmlSchemaAttribute))
return null;
XmlSchemaAttribute attr = (XmlSchemaAttribute)obj;
if(attr.AttributeType!=null)
return FindType(attr.AttributeType);
else
if(attr.SchemaTypeName.Name.CompareTo("anyType")==0) return typeof(object);
return null;
}
private static void ShowCompileError(object sender, ValidationEventArgs e)
{
Console.WriteLine("Validation Error: {0}", e.Message);
}
private System.Type FindType(object obj)
{
if(obj.GetType()==typeof(XmlSchemaSimpleType))
{
XmlSchemaSimpleType simpleType = (XmlSchemaSimpleType)obj;
return simpleType.Datatype.ValueType;
}
else if(obj.GetType()==typeof(XmlSchemaComplexType))
{
XmlSchemaComplexType complexType = (XmlSchemaComplexType)obj;
return complexType.Datatype.ValueType;
}
else
{
XmlSchemaDatatype datatype = (XmlSchemaDatatype)obj;
return datatype.ValueType;
}
}
}
}
转载于:https://www.cnblogs.com/sqwang/archive/2005/03/10/116493.html
最后
以上就是不安大树为你收集整理的用XSD判断XML文件中元素和属性的全部内容,希望文章能够帮你解决用XSD判断XML文件中元素和属性所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复