高效 XML 开发的 C# 编程技巧

时间:2023-02-12 12:57:53

最大限度地提高高效可靠的 XML 解决方案的技能

高效 XML 开发的 C# 编程技巧

XML(eXtensible Markup Language)于1996年由万维网联盟(W3C)首次提出,并于1998年成为官方推荐。XML被设计为一种数据交换格式,有助于简化不同应用程序和平台之间交换结构化数据的过程. 自推出以来,XML 已成为使用最广泛的标记语言之一,用于在 Internet 上存储和交换数据,并在 Web 服务、移动应用程序和其他应用程序的开发中继续发挥重要作用。

作为一名 C# 程序员,您可能会发现自己在各种环境中使用 XML,无论是在桌面应用程序、Web 服务还是移动应用程序中。在本文中,我们将提供一些使用 C# 进行有效 XML 开发的技巧和最佳实践。

使用 System.Xml.Linq

System.Xml.Linq 和 System.Xml 是 .NET 框架中的两个命名空间,用于在 C# 中处理 XML 数据。这两个名称空间都提供了一种解析和操作 XML 数据的方法,但它们在几个关键方面有所不同。这是 System.Xml.Linq 和 System.Xml 的比较:

  • 使用方便

System.Xml.Linq 通常被认为比 System.Xml 更易于使用。它为处理 XML 数据提供了更简洁和更具表现力的语法,并且无需编写与 System.Xml 一样多的代码。

下面是一个示例,它演示了 System.Xml.Linq 在 C# 中在内存中构造 XML 数据的易用性:

using System;
using System.Xml.Linq;

namespace XmlLinqExample
{
class Program
{
static void Main(string[] args)
{
// Create an XElement to represent the library element
XElement library = new XElement("library",
new XElement("book",
new XElement("title", "The Great Gatsby"),
new XElement("author", "F. Scott Fitzgerald"),
new XElement("publisher", "Charles Scribner's Sons"),
new XElement("isbn", "978-0684801520")
),
new XElement("book",
new XElement("title", "To Kill a Mockingbird"),
new XElement("author", "Harper Lee"),
new XElement("publisher", "J. B. Lippincott & Co."),
new XElement("isbn", "978-0446310789")
)
);

// Display the XML on the console
Console.WriteLine(library.ToString());

Console.ReadLine();
}
}
}

在此示例中,使用 XElement 对象来表示​​library​​元素,并使用嵌套的 XElement 对象来表示元素​​book​​。代码易读易懂,展示了System.Xml.Linq在内存中构造XML数据的简洁明了的语法。

如果您使用 System.Xml 编写上面的示例

using System;
using System.Xml;

namespace XmlExample
{
class Program
{
static void Main(string[] args)
{
// Create an XmlDocument to represent the library element
XmlDocument xmlDoc = new XmlDocument();
XmlElement library = xmlDoc.CreateElement("library");
xmlDoc.AppendChild(library);

// Create the first book element
XmlElement book = xmlDoc.CreateElement("book");
library.AppendChild(book);

XmlElement title = xmlDoc.CreateElement("title");
title.InnerText = "The Great Gatsby";
book.AppendChild(title);

XmlElement author = xmlDoc.CreateElement("author");
author.InnerText = "F. Scott Fitzgerald";
book.AppendChild(author);

XmlElement publisher = xmlDoc.CreateElement("publisher");
publisher.InnerText = "Charles Scribner's Sons";
book.AppendChild(publisher);

XmlElement isbn = xmlDoc.CreateElement("isbn");
isbn.InnerText = "978-0684801520";
book.AppendChild(isbn);

// Create the second book element
book = xmlDoc.CreateElement("book");
library.AppendChild(book);

title = xmlDoc.CreateElement("title");
title.InnerText = "To Kill a Mockingbird";
book.AppendChild(title);

author = xmlDoc.CreateElement("author");
author.InnerText = "Harper Lee";
book.AppendChild(author);

publisher = xmlDoc.CreateElement("publisher");
publisher.InnerText = "J. B. Lippincott & Co.";
book.AppendChild(publisher);

isbn = xmlDoc.CreateElement("isbn");
isbn.InnerText = "978-0446310789";
book.AppendChild(isbn);

// Display the XML on the console
Console.WriteLine(xmlDoc.OuterXml);

Console.ReadLine();
}
}
}

在此示例中,XmlDocument 对象用于表示​​library​​元素,XmlElement 对象用于表示​​book​​元素及其子元素。与使用 System.Xml.Linq 的等效代码相比,该代码更加冗长并且需要更多步骤,但它演示了如何使用 System.Xml 在内存中构造 XML 数据。

此示例突出显示了 System.Xml 在 C# 中处理 XML 数据的局限性,与 System.Xml.Linq 相比,System.Xml.Linq 提供了更简洁和更具表现力的语法,并且无需编写尽可能多的代码。

  • 查询语言

System.Xml.Linq 使用 LINQ(语言集成查询)查询 XML 数据,而 System.Xml 使用 XPath。LINQ 是一种内置于 C# 中的强大而灵活的查询语言,它为查询 XML 数据提供了更直观、更简洁的语法。

下面是一个示例,演示如何使用 System.Xml.Linq 的查询语言 (LINQ) 在 C# 中查询 XML 数据:

using System;
using System.Xml.Linq;

namespace XmlLinqExample
{
class Program
{
static void Main(string[] args)
{
// Load the XML document using XDocument.Load
XDocument xmlDoc = XDocument.Load("books.xml");

// Use LINQ to query the XML document
var books = from book in xmlDoc.Descendants("book")
where book.Element("author").Value == "Harper Lee"
select new
{
Title = book.Element("title").Value,
Author = book.Element("author").Value,
Publisher = book.Element("publisher").Value,
ISBN = book.Element("isbn").Value
};

// Iterate through the results and display the book information
foreach (var book in books)
{
Console.WriteLine("Title: " + book.Title);
Console.WriteLine("Author: " + book.Author);
Console.WriteLine("Publisher: " + book.Publisher);
Console.WriteLine("ISBN: " + book.ISBN);
Console.WriteLine();
}

Console.ReadLine();
}
}
}

在此示例中,使用 方法将 XML 文档加载到 XDocument 对象中​​XDocument.Load​​。然后,使用 LINQ 查询 XML 文档并提取有关 Harper Lee 所著书籍的信息。结果显示在控制台上。

此示例演示了使用 LINQ 在 C# 中查询 XML 数据的强大功能和简单性,与使用 System.Xml 的 XPath 相比,后者可能更复杂且更难理解。

下面是一个示例,演示了如何使用 System.Xml 和 XPath 在 C# 中查询 XML 数据:

using System;
using System.Xml;

namespace XmlExample
{
class Program
{
static void Main(string[] args)
{
// Load the XML document using XmlDocument
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("books.xml");
// Use XPath to query the XML document
XmlNodeList bookNodes = xmlDoc.SelectNodes("/library/book[author='Harper Lee']");
// Iterate through the results and display the book information
foreach (XmlNode bookNode in bookNodes)
{
Console.WriteLine("Title: " + bookNode["title"].InnerText);
Console.WriteLine("Author: " + bookNode["author"].InnerText);
Console.WriteLine("Publisher: " + bookNode["publisher"].InnerText);
Console.WriteLine("ISBN: " + bookNode["isbn"].InnerText);
Console.WriteLine();
}
Console.ReadLine();
}
}
}

在此示例中,使用 方法将 XML 文档加载到 XmlDocument 对象中​​Load​​。然后,XPath 用于查询 XML 文档并提取有关 Harper Lee 所著书籍的信息。结果显示在控制台上。

  • 性能

System.Xml.Linq 通常比 System.Xml 更快、更高效,尤其是对于大型 XML 文档。对于在 C# 中处理 XML 数据,System.Xml.Linq 通常被认为比 System.Xml 更快、更高效。这是因为 System.Xml.Linq 为 XML 数据使用了更优化的内存表示,并且它旨在与 LINQ 和 .NET 框架很好地配合使用。例如,System.Xml.Linq 使用延迟加载,这意味着它只在需要时将 XML 数据加载到内存中,而不是一次加载整个 XML 文档。这可以显着提高大型 XML 文档的性能。

此外,System.Xml.Linq 为处理 XML 数据提供了更简洁、更具表现力的语法,这可以使您的代码更易于编写、理解和维护。反过来,这可以提高性能,并减少开发时间和工作量。

虽然 System.Xml.Linq 相对于 System.Xml 的性能改进可能因具体场景和 XML 文档的大小而异,但通常建议对大多数 XML 开发项目使用 System.Xml.Linq,因为它提供了一个在 C# 中使用 XML 数据的更现代和高效的方式。

  • 面向对象的表示

System.Xml.Linq 提供了 XML 数据的面向对象表示,使您可以更轻松地在 C# 代码中操作数据。使用 System.Xml,您必须处理原始 XML 数据,这可能会更困难且更不直观。

下面是一个代码示例,它演示了 C# 中 System.Xml.Linq 的面向对象表示形式:

using System;
using System.Xml.Linq;

namespace XmlLinqExample
{
class Program
{
static void Main(string[] args)
{
// Create an XElement to represent the library element
XElement library = new XElement("library",
new XElement("book",
new XElement("title", "The Great Gatsby"),
new XElement("author", "F. Scott Fitzgerald"),
new XElement("publisher", "Charles Scribner's Sons"),
new XElement("isbn", "978-0684801520")
),
new XElement("book",
new XElement("title", "To Kill a Mockingbird"),
new XElement("author", "Harper Lee"),
new XElement("publisher", "J. B. Lippincott & Co."),
new XElement("isbn", "978-0446310789")
)
);

// Modify the XML data using object-oriented methods
XElement firstBook = library.Elements("book").First();
firstBook.Element("title").Value = "The Great Gatsby (Revised Edition)";

// Display the XML on the console
Console.WriteLine(library.ToString());

Console.ReadLine();
}
}
}

该代码演示了使用面向对象的方法来修改 XML 数据,例如​​First​​检索第一个​​book​​元素的方法和​​Element​​检索​​title​​元素的方法。这使得以自然和直观的方式处理 XML 数据变得容易,并且消除了编写复杂代码或使用 XPath 的需要。

  • 可扩展性

System.Xml.Linq 被设计为可扩展的,这意味着您可以创建自己的自定义类和对象来处理 XML 数据。使用 System.Xml,您必须使用原始 XML 数据,这会使扩展功能变得更加困难。

以下代码示例演示了 C# 中 System.Xml.Linq 的可扩展性:

using System;
using System.Xml.Linq;

namespace XmlLinqExample
{
public static class BookExtensions
{
public static string GetPrice(this XElement book)
{
return "$" + (double.Parse(book.Element("price").Value) * 1.13).ToString("0.00");
}
}

class Program
{
static void Main(string[] args)
{
// Load the XML document using XDocument.Load
XDocument xmlDoc = XDocument.Load("books.xml");

// Use LINQ to query the XML document
var books = from book in xmlDoc.Descendants("book")
select new
{
Title = book.Element("title").Value,
Author = book.Element("author").Value,
Publisher = book.Element("publisher").Value,
ISBN = book.Element("isbn").Value,
Price = book.GetPrice()
};

// Iterate through the results and display the book information
foreach (var book in books)
{
Console.WriteLine("Title: " + book.Title);
Console.WriteLine("Author: " + book.Author);
Console.WriteLine("Publisher: " + book.Publisher);
Console.WriteLine("ISBN: " + book.ISBN);
Console.WriteLine("Price: " + book.Price);
Console.WriteLine();
}

Console.ReadLine();
}
}
}

在此示例中,为 XElement 对象定义了名为 的自定义扩展方法​​GetPrice​​,该方法计算一本书在添加销售税后的价格。此扩展方法可用于 LINQ 查询,以轻松检索 XML 文档中每本书的价格。

此示例演示了 System.Xml.Linq 的可扩展性,因为它允许您轻松地将自定义功能添加到 XElement 类,例如自定义扩展方法,以满足您的 XML 开发项目的特定需求。通过使用 System.Xml.Linq,您可以编写灵活且可扩展的代码,这些代码可以很容易地适应不断变化的需求,并且可以更轻松地在 C# 应用程序中处理 XML 数据。

总之,System.Xml.Linq 是一种在 C# 中处理 XML 数据的更现代、更高效的方法,建议将其用于大多数 XML 开发项目。

验证 XML 数据

XSD 是一种基于 XML 的语言,用于定义 XML 文档的结构和内容。使用 XML 数据时,验证数据以确保它符合预期的结构和内容非常重要。您可以使用 C# 中的 XSD 来验证您的 XML 数据,方法是使用 XmlReader 类或使用 LINQ to XML 中的 XDocument 类。

下面是一个代码示例,演示如何在 C# 中使用 System.Xml.Linq 通过 XSD(XML 架构定义)验证 XML 数据:

using System;
using System.Xml.Linq;
using System.Xml.Schema;

namespace XmlLinqValidationExample
{
class Program
{
static void Main(string[] args)
{
// Load the XML document using XDocument.Load
XDocument xmlDoc = XDocument.Load("books.xml");

// Validate the XML document against the XSD schema
XmlSchemaSet schemaSet = new XmlSchemaSet();
schemaSet.Add("", "books.xsd");
bool hasErrors = false;
xmlDoc.Validate(schemaSet, (o, e) =>
{
Console.WriteLine("Validation error: " + e.Message);
hasErrors = true;
});

if (!hasErrors)
{
Console.WriteLine("XML validation completed successfully.");
}

Console.ReadLine();
}
}
}

​Load​​在此示例中,使用System.Xml.Linq中的方法将 XML 文档加载到 XDocument 对象中。使用该方法将 XSD 架构加载到 XmlSchemaSet 对象中​​Add​​,然后使用该​​Validate​​方法针对 XmlSchemaSet 验证 XDocument 对象。验证过程由传递给该方法的事件处理程序处理,​​Validate​​如果发现任何验证错误,该方法将在控制台上显示验证错误。

XML序列化

XML 序列化是 C# 中的一项功能,可让您轻松地将对象与 XML 相互转换。这在处理 XML 数据时非常有用,因为它允许您在 C# 代码中将数据作为对象来处理,而不必处理原始 XML。您可以使用 C# 中的 XmlSerializer 类来执行 XML 序列化,并且可以通过使用对象的属性来自定义序列化过程。

下面是一个代码示例,演示如何使用 XML 序列化在 C# 中高效地将对象与 XML 相互转换:

using System;
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;

namespace XmlSerializationExample
{
[XmlRoot("Library")]
public class Library
{
[XmlElement("Book")]
public List<Book> Books { get; set; }
}

public class Book
{
[XmlElement("Title")]
public string Title { get; set; }

[XmlElement("Author")]
public string Author { get; set; }

[XmlElement("Publisher")]
public string Publisher { get; set; }

[XmlElement("ISBN")]
public string ISBN { get; set; }
}

class Program
{
static void Main(string[] args)
{
// Create a Library object and add some books
Library library = new Library();
library.Books = new List<Book>();
library.Books.Add(new Book { Title = "The Great Gatsby", Author = "F. Scott Fitzgerald", Publisher = "Charles Scribner's Sons", ISBN = "978-0684801520" });
library.Books.Add(new Book { Title = "To Kill a Mockingbird", Author = "Harper Lee", Publisher = "J. B. Lippincott & Co.", ISBN = "978-0446310789" });

// Serialize the Library object to an XML file
XmlSerializer serializer = new XmlSerializer(typeof(Library));
using (TextWriter writer = new StreamWriter("library.xml"))
{
serializer.Serialize(writer, library);
}

// Deserialize the XML file to a Library object
Library deserializedLibrary;
using (TextReader reader = new StreamReader("library.xml"))
{
deserializedLibrary = (Library)serializer.Deserialize(reader);
}

// Display the deserialized Library object on the console
foreach (Book book in deserializedLibrary.Books)
{
Console.WriteLine("Title: " + book.Title);
Console.WriteLine("Author: " + book.Author);
Console.WriteLine("Publisher: " + book.Publisher);
Console.WriteLine("ISBN: " + book.ISBN);
Console.WriteLine();
}

Console.ReadLine();
}
}
}

​Library​​在此示例中,为和​​Book​​对象定义了类,并且​​XmlRoot​​和​​XmlElement​​属性用于指定对象的 XML 表示形式。该类​​XmlSerializer​​用于将​​Library​​对象序列化为 XML 文件,并将 XML 文件反序列化回​​Library​​对象。

JSON格式

下面是一个代码示例,演示了如何使用 JsonConvert.DeserializeXNode 在 C# 中将 JSON 字符串转换为 XML 字符串:

using System;
using Newtonsoft.Json;

namespace JsonToXmlExample
{
class Program
{
static void Main(string[] args)
{
// Define a JSON string
string json = @"{
""library"": {
""book"": [
{
""title"": ""The Great Gatsby"",
""author"": ""F. Scott Fitzgerald"",
""publisher"": ""Charles Scribner's Sons"",
""isbn"": ""978-0684801520""
},
{
""title"": ""To Kill a Mockingbird"",
""author"": ""Harper Lee"",
""publisher"": ""J. B. Lippincott & Co."",
""isbn"": ""978-0446310789""
}
]
}
}";

// Convert the JSON string to an XNode
var xml = JsonConvert.DeserializeXNode(json, "Root");

// Display the XML on the console
Console.WriteLine(xml);

Console.ReadLine();
}
}
}

此示例演示了如何使用​​DeserializeXNode​​Newtonsoft.Json 库中的方法在 C# 中将 JSON 字符串转换为 XML 字符串,并突出了此方法的简单性和易用性。通过使用​​DeserializeXNode​​,您可以使用一行代码轻松高效地将 JSON 数据转换为 XML 数据。

下面的代码示例演示了如何在 C# 中将 XML 字符串转换为 JSON 字符串:

using System;
using Newtonsoft.Json;

namespace XmlToJsonExample
{
class Program
{
static void Main(string[] args)
{
// Define an XML string
string xml = @"<library>
<book>
<title>The Great Gatsby</title>
<author>F. Scott Fitzgerald</author>
<publisher>Charles Scribner's Sons</publisher>
<isbn>978-0684801520</isbn>
</book>
<book>
<title>To Kill a Mockingbird</title>
<author>Harper Lee</author>
<publisher>J. B. Lippincott & Co.</publisher>
<isbn>978-0446310789</isbn>
</book>
</library>";

// Convert the XML string to a JSON string
string json = JsonConvert.SerializeXNode(xml, Formatting.Indented);

// Display the JSON on the console
Console.WriteLine(json);

Console.ReadLine();
}
}
}

此示例演示了如何使用​​SerializeXNode​​Newtonsoft.Json 库中的方法在 C# 中将 XML 字符串转换为 JSON 字符串,并突出了此方法的简单性和易用性。通过使用​​SerializeXNode​​,您可以使用一行代码轻松高效地将 XML 数据转换为 JSON 数据。

XML数据

XML CDATA(字符数据)是一种在 XML 文档中转义字符数据的方法。在 XML 文档中,一些字符被保留用于定义文档的结构和语法,例如用于定义元素的尖括号(< 和 >)。如果您需要将这些字符作为元素字符数据的一部分,则必须使用实体引用(例如​​&lt;​​and ​​&gt;​​)或 CDATA 部分对它们进行转义。

CDATA 部分以 sequence 开始​​<![CDATA[​​并以 sequence 结束​​]]>​​。这两个序列之间的所有内容都被视为字符数据,即使它包含通常保留用于定义文档结构和语法的字符。例如:

<element>
<![CDATA[This is some character data that includes < and > characters.]]>
</element>

​<![CDATA[​​在此示例中,和序列之间的字符数据​​]]>​​被视为文字文本,而不是作为 XML 进行解析。这允许您将原本在 XML 文档中作为字符数据的一部分视为保留的字符包括在内。

另一个示例演示了如何在 C# 中使用 HTTP 调用基于 SOAP 的 Web 服务并在 CDATA 部分中传递过滤器参数:

using System;
using System.Net;
using System.Text;

namespace SoapWebServiceExample
{
class Program
{
static void Main(string[] args)
{
// Define the web service endpoint
string endpoint = "https://example.com/books/service.asmx";

// Define the filter parameter in XML format inside a CDATA section
string filter = @"<![CDATA[
<filter>
<title>The Great Gatsby</title>
</filter>
]]>";

// Define the SOAP request body
string soapRequest = @"<?xml version=""1.0"" encoding=""utf-8""?>
<soap:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"">
<soap:Body>
<GetBooks xmlns=""http://example.com/books"">
<filter>" + filter + @"</filter>
</GetBooks>
</soap:Body>
</soap:Envelope>";

// Create a web request
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(endpoint);
request.Method = "POST";
request.ContentType = "text/xml; charset=utf-8";
request.Headers.Add("SOAPAction", "http://example.com/books/GetBooks");

// Write the SOAP request body to the request stream
byte[] requestBytes = Encoding.UTF8.GetBytes(soapRequest);
request.ContentLength = requestBytes.Length;
using (var requestStream = request.GetRequestStream())
{
requestStream.Write(requestBytes, 0, requestBytes.Length);
}

// Send the request and get the response
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

// Read the response body
string responseBody;
using (var responseStream = response.GetResponseStream())
{
using (var reader = new System.IO.StreamReader(responseStream))
{
responseBody = reader.ReadToEnd();
}
}

// Display the response body on the console
Console.WriteLine(responseBody);

Console.ReadLine();
}
}
}

在此示例中,​​filter​​参数在 CDATA 部分内定义,以转义为定义 XML 文档的结构和语法而保留的任何字符。变量的​​soapRequest​​定义方式与前面示例中的相同,但这次它​​filter​​在 CDATA 部分中包含了参数。其余代码保持不变,它演示了如何向 Web 服务发送 SOAP 请求并接收响应。

使用 XML 记事本

XML Notepad 是微软开发的一款免费的轻量级 XML 编辑器。它为查看、编辑和创建 XML 文档提供了一个简单直观的界面。使用 XML 记事本,您可以轻松查看 XML 文档的结构,包括它的元素、属性和值,以及它的层次关系。该编辑器还提供了根据指定模式验证 XML 文档以及格式化和缩进 XML 数据以使其更易于阅读和理解的功能。

XML Notepad 的主要优点之一是它的易用性。它旨在成为一个简单明了的 XML 编辑器,使其成为刚开始使用 XML 或需要快速简便的方法来查看和编辑 XML 数据的开发人员的理想选择。此外,XML 记事本是一种快速高效的工具,即使在处理大型 XML 文档时也是如此,因此您可以轻松地处理数据而不必担心性能问题。

ML Notepad 对于任何需要处理 XML 数据的人来说都是一个有用的工具。无论您是开发人员、数据分析师,还是只是需要查看或编辑 XML 数据的人,XML Notepad 都提供了一种简单高效的方式来完成工作。


Xml记事本

XML 记事本为浏览和编辑 XML 文档提供了一个简单直观的用户界面。XML 记事本是……

​微软.github.io​

使用 XSLT 进行转换

XSLT(可扩展样式表语言转换)是一种功能强大且灵活的语言,用于将 XML 数据转换为其他格式。

XSLT 的一个优点是它与平台无关,可用于将数据转换为多种格式,包括 HTML、CSV 和其他文本文件。这使它成为一种用于数据交换和集成的多功能工具,因为它允许您将数据从一种格式转换为另一种格式,而无需为每种格式编写自定义代码。

  • 怎么运行的

下面是一个 C# 代码示例,演示了如何使用 XSLT 将 XML 数据转换为 CSV 文件:

using System;
using System.IO;
using System.Xml;
using System.Xml.Xsl;

namespace XsltExample
{
class Program
{
static void Main(string[] args)
{
// Load the XML data
XmlDocument xmlData = new XmlDocument();
xmlData.Load("books.xml");

// Load the XSLT stylesheet
XslCompiledTransform xslt = new XslCompiledTransform();
xslt.Load("books-to-csv.xsl");

// Transform the XML data into a CSV file
using (var writer = new StreamWriter("books.csv"))
{
xslt.Transform(xmlData, null, writer);
}

Console.WriteLine("XML data transformed to CSV file.");
Console.ReadLine();
}
}
}

在此示例中,使用 方法将 XML 数据加载到​​XmlDocument​​对象中​​Load​​。使用该方法将 XSLT 样式表加载到​​XslCompiledTransform​​对象中​​Load​​。然后使用该​​Transform​​方法将 XSLT 样式表应用于 XML 数据,并使用对象将输出写入 CSV 文件​​StreamWriter​​。

本例中使用的 XSLT 样式表定义了将 XML 数据转换为 CSV 格式的转换规则。XSLT 样式表未包含在本示例中,但您可以编写自己的样式表以满足您的特定需要。

以下是可用于将 XML 数据转换为 CSV 文件的 XSLT 样式表示例:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>

<xsl:template match="books">
<xsl:text>Title,Author,Publisher,PublishedDate</xsl:text>
<xsl:text> </xsl:text>
<xsl:apply-templates select="book"/>
</xsl:template>

<xsl:template match="book">
<xsl:value-of select="title"/>
<xsl:text>,</xsl:text>
<xsl:value-of select="author"/>
<xsl:text>,</xsl:text>
<xsl:value-of select="publisher"/>
<xsl:text>,</xsl:text>
<xsl:value-of select="publishedDate"/>
<xsl:text> </xsl:text>
</xsl:template>

</xsl:stylesheet>
  • C# 扩展

下面是一个 C# 代码示例,演示了如何将 C# 扩展传递给 XSLT 转换器:

using System;
using System.IO;
using System.Xml;
using System.Xml.Xsl;

namespace XsltWithExtensionExample
{
class Program
{
static void Main(string[] args)
{
// Load the XML data
XmlDocument xmlData = new XmlDocument();
xmlData.Load("books.xml");

// Load the XSLT stylesheet
XslCompiledTransform xslt = new XslCompiledTransform();
xslt.Load("books-to-csv.xsl");

// Create the XsltArgumentList to pass to the XSLT transformer
XsltArgumentList argsList = new XsltArgumentList();

// Add a C# extension to the XsltArgumentList
argsList.AddExtensionObject("urn:my-extension", new MyExtension());

// Transform the XML data using the XSLT stylesheet and C# extension
using (var writer = new StreamWriter("books.csv"))
{
xslt.Transform(xmlData, argsList, writer);
}

Console.WriteLine("XML data transformed to CSV file using C# extension.");
Console.ReadLine();
}
}

public class MyExtension
{
// Example C# extension method
public string FormatDate(string date)
{
return DateTime.Parse(date).ToShortDateString();
}
}
}

在这个例子中,XML 数据被加载到一个​​XmlDocument​​对象中,XSLT 样式表被加载到一个​​XslCompiledTransform​​对象中,方式与前面的示例相同。

然后​​XsltArgumentList​​创建 ,并使用该​​AddExtensionObject​​方法将 C# 扩展对象添加到列表中。在此示例中,扩展对象是一个名为 的类的实例​​MyExtension​​,其中包含用于格式化日期的方法。

最后,该​​Transform​​方法用于使用 XSLT 样式表和 C# 扩展来转换 XML 数据。XsltArgumentList​​Transform​​作为参数传递给方法,允许 XSLT 样式表访问 C# 扩展。

具有 XSLT 转换的 C# 扩展可用于执行自定义处理或访问 XSLT 本身不可用的功能。C# 扩展可以包含您需要的任何逻辑或功能,并且可以在多个 XSLT 转换中重复使用。

下面是一个 XSLT 样式表示例,它演示了如何使用上一个示例中的 C# 扩展:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:my="urn:my-extension">
<xsl:output method="text"/>

<xsl:template match="books">
<xsl:text>Title,Author,Publisher,PublishedDate</xsl:text>
<xsl:text> </xsl:text>
<xsl:apply-templates select="book"/>
</xsl:template>

<xsl:template match="book">
<xsl:value-of select="title"/>
<xsl:text>,</xsl:text>
<xsl:value-of select="author"/>
<xsl:text>,</xsl:text>
<xsl:value-of select="publisher"/>
<xsl:text>,</xsl:text>
<xsl:value-of select="my:FormatDate(publishedDate)" />
<xsl:text> </xsl:text>
</xsl:template>

</xsl:stylesheet>

在此示例中,XSLT 样式表已更新为包含 C# 扩展 ( ​​xmlns:my="urn:my-extension"​​) 的名称空间。命名空间用于限定对模板 ( )​​FormatDate​​中方法的调用。​​book​​​​my:FormatDate(publishedDate)​

  • MSXML 扩展

MSXML 是 XSLT 的扩展,它提供了用于转换 XML 数据的附加功能。MSXML 提供的一些功能包括:

  • 标准 XSLT 中不可用的许多附加功能和能力,例如执行字符串操作和格式化、数学计算以及日期和时间操作的能力。
  • 能够以分层和面向对象的方式处理 XML 数据,从而更容易处理复杂的 XML 数据结构。
  • 一种快速高效的 XSLT 处理器,针对在 Microsoft Windows 环境中的使用进行了优化。

下面是一个 C# 示例,它演示了如何使用​​msxsl:node-set​​MSXML 中的函数将节点集转换为 XSLT 样式表中的字符串:

using System;
using System.Xml;
using System.Xml.Xsl;

namespace MsxmlNodeSetExample
{
class Program
{
static void Main(string[] args)
{
// Load the XML data
XmlDocument xmlData = new XmlDocument();
xmlData.Load("books.xml");

// Load the XSLT stylesheet
XslCompiledTransform xslt = new XslCompiledTransform();
xslt.Load("books-to-csv.xsl");

// Transform the XML data using the XSLT stylesheet
using (var writer = new StreamWriter("books.csv"))
{
xslt.Transform(xmlData, null, writer);
}

Console.WriteLine("XML data transformed to CSV file.");
Console.ReadLine();
}
}
}
<?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">
<xsl:output method="text"/>

<xsl:template match="books">
<xsl:text>Title,Author,Publisher,PublishedDate</xsl:text>
<xsl:text> </xsl:text>
<xsl:apply-templates select="book"/>
</xsl:template>

<xsl:template match="book">
<xsl:value-of select="title"/>
<xsl:text>,</xsl:text>
<xsl:value-of select="author"/>
<xsl:text>,</xsl:text>
<xsl:value-of select="publisher"/>
<xsl:text>,</xsl:text>
<xsl:value-of select="msxsl:node-set(publishedDate)/@formatted" />
<xsl:text> </xsl:text>
</xsl:template>

</xsl:stylesheet>

在此示例中,XML 数据和 XSLT 样式表的加载方式与上一示例相同。该​​msxsl:node-set​​函数在​​book​​模板中用于将​​publishedDate​​节点转换为节点集并访问​​formatted​​属性。

该​​msxsl:node-set​​函数是 XSLT 的 MSXML 扩展,允许您将节点集转换为字符串,从而更轻松地处理 XSLT 样式表中的复杂 XML 数据结构。通过使用该​​msxsl:node-set​​函数,您可以利用 MSXML 提供的全部 XML 数据操作功能,包括处理节点和节点集、执行字符串操作和格式化,以及以分层和面向对象的方式访问 XML 数据。