如何在 C# 中创建 XSD & XSLT 处理器
一个很好的演示,展示了如何使用 C# 实现 XSD & XSLT 处理器。
引言
XSD(XML 模式定义)用于验证 XML 文件的结构和数据类型,通常用于在开始处理之前验证输入 XML 文件是否被篡改。
XSLT(可扩展样式表语言)允许您将 XML 文件转换为另一种格式,例如:XML 到 XML,或 XML 到 HTML 等。
要了解有关上述处理器的更多信息,我建议您访问以下链接:
背景
这篇文章可能对具有一些 C# 和 XML 编程基础的中间级开发人员有用。
Using the Code
A) 操作流程
应用程序的主要思想是:
- 读取本地 XML 文件(使用
XmlReader
类) - 指定用于通过
XmlReaderSettings
类 验证 XML 模式的 XSD 文件 - 如果 XSD 处理器运行成功,则 XSLT 处理器(使用
XslCompiledTransform
类)会将当前的 XML 文件转换为另一个文件(XML 文件)。
以下模式将更好地解释它:
作为我们应用程序的输入,我们将拥有:
1) XML 文件 (命名为 oldFile.xml)
<?xml version="1.0" encoding="iso-8859-1"?>
<Application name="appXSD_XSLT">
<TopObject name="topObject">
<Actions>
<Synchronization nDate="20120909">
<Events>
<Event index="0" action="insert"
name="product1" location="paris"/>
<Event index="1" action="delete"
name="product2" location="lille"/>
</Events>
</Synchronization>
</Actions>
</TopObject>
</Application>
2) XSD 文件 (命名为 schema.xsd)
<?xml version="1.0" encoding="iso-8859-1"?>
<xs:schema
elementFormDefault="qualified"
xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="Application">
<xs:complexType>
<xs:sequence>
<xs:element name="TopObject">
<xs:complexType>
<xs:sequence>
<xs:element name="Actions">
<xs:complexType>
<xs:sequence>
<xs:element name="Synchronization">
<xs:complexType>
<xs:sequence>
<xs:element name="Events">
<xs:complexType>
<xs:sequence>
<xs:element name="Event"
maxOccurs="unbounded">
<xs:complexType>
<xs:attribute name="action"
type="xs:string" use="required" />
<xs:attribute name="index"
type="xs:integer" use="required"/>
<xs:attribute name="name"
type="xs:string"/>
<xs:attribute name="location"
type="xs:string"/>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name="nDate"
type="xs:string"/>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name="name" type="xs:string" />
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name="name" type="xs:string" />
</xs:complexType>
</xs:element>
</xs:schema>
3) XSLT 文件(命名为 transformation.xslt)
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt"
exclude-result-prefixes="msxsl">
<xsl:output method="xml" indent="yes"/>
<xsl:template
match="/Application/TopObject/Actions/Synchronization/Events">
<Application>
<Actions>
<xsl:apply-templates select="Event"></xsl:apply-templates>
</Actions>
</Application>
</xsl:template>
<xsl:variable name="lowerCase"
select="'abcdefghijklmnopqrstuvwxyz'"/>
<xsl:variable name="upperCase"
select="'ABCDEFGHIJKLMNOPQRSTUVWXYZ'"/>
<xsl:template match="Event">
<Product action="{@action}" id="{@index}">
<givenName value="{concat(
translate(substring(@name, 1, 1), $lowerCase, $upperCase),
translate(substring(@name,2), $upperCase, $lowerCase))
}">
</givenName>
<location value="{concat(
translate(substring(@location, 1, 1), $lowerCase, $upperCase),
translate(substring(@location,2), $upperCase, $lowerCase))
}">
</location>
</Product>
</xsl:template>
</xsl:stylesheet>
B) 源代码
C# 代码
#region XSD Validation
static bool _isValid = true;
/// <summary>
/// Validation du schéma XML
/// </summary>
public static void RunXsdValidation()
{
var fileInUse = "XSD";
try
{
Console.WriteLine(String.Format("Starting XSD process."));
var xmlSettings = new XmlReaderSettings();
xmlSettings.Schemas.Add("", "../../Content/schema.xsd");
xmlSettings.ValidationType = ValidationType.Schema;
xmlSettings.ValidationEventHandler += TestValidationEventHandler;
fileInUse = "XML";
var xmlFile = XmlReader.Create("../../Content/oldFile.xml", xmlSettings);
while (xmlFile.Read()) { }
if (_isValid)
{
Console.WriteLine(String.Format("XML Schema is valid."));
}
else
{
Console.WriteLine("Error occurs on XML validation.
XML schema not valid.");
Environment.Exit(1);
}
}
catch (FileNotFoundException ex)
{
if (fileInUse.Equals("XSD"))
{
Console.WriteLine("XSD file not found \nError: '" +
ex.Message + "'");
Environment.Exit((int)ExitCode.Error);
}
else if (fileInUse.Equals("XML"))
{
Console.WriteLine("XML file not found.\nError : '" +
ex.Message + "'");
Environment.Exit((int)ExitCode.Error);
}
}
catch (Exception ex)
{
Console.WriteLine("Error occurs on XML validation.
XML schema not valid. \nError: " + ex.Message);
Environment.Exit(1);
}
}
public static void TestValidationEventHandler(object sender, ValidationEventArgs args)
{
_isValid = false;
}
#endregion
#region XSLT Transformation
/// <summary>
/// Transformer le fichier XML à partir d'un fichier XSLT
/// </summary>
public static void RunXslt()
{
var fileInUse = "XSLT";
try
{
Console.WriteLine(String.Format("starting XSLT process"));
// Load the style sheet.
var xslt = new XslCompiledTransform();
xslt.Load("../../Content/transformation.xslt");
// Execute the transform and output the results to a file.
fileInUse = "XML";
xslt.Transform
("../../Content/oldFile.xml", "../../Content/newFile.xml");
Console.WriteLine(String.Format("Fail occurs on transformation."));
}
catch (FileNotFoundException ex)
{
if (fileInUse.Equals("XSLT"))
{
Console.WriteLine("XSLT file not found.");
Environment.Exit(1);
}
else if (fileInUse.Equals("XML"))
{
Console.WriteLine("XML file not found.");
Environment.Exit((int)ExitCode.Error);
}
}
catch (Exception ex)
{
Console.WriteLine
("Fail occurs on transformation. \nError : " + ex.Message);
Environment.Exit((int)ExitCode.Error);
}
}
#endregion
private enum ExitCode : int
{
Success = 0,
Error = 1,
}
static void Main(string[] args)
{
//use XML Schema to validate.
RunXsdValidation();
//Transformation.
RunXslt();
Environment.Exit((int)ExitCode.Success);
}
C) 结果
运行应用程序后,输出将是:
newFile.xml:创建在应用程序根文件夹中的 Content 文件夹中。
<?xml version="1.0" encoding="utf-8"?>
<Application>
<Actions>
<Product action="insert" id="0">
<givenName value="Product1" />
<location value="Paris" />
</Product>
<Product action="delete" id="1">
<givenName value="Product2" />
<location value="Lille" />
</Product>
</Actions>
</Application>
最后
希望您喜欢这篇文章。 尝试下载源代码。 请在下方发布您的问题和评论。
历史
- v1 2016/10/21:初始版本