如何:转换节点片段

在转换 XmlDocumentXPathDocument 对象中包含的数据时,XSLT 转换应用于整个文档。 换句话说,如果你传入文档根节点以外的一个节点,并不能防止转换进程访问已加载文档的所有节点。 若要转换节点片段,必须创建一个仅包含节点片段的独立对象,并将该对象传递给 Transform 方法。

过程

转换节点片断

  1. 创建一个包含源文档的对象。

  2. 找到要转换的节点片断。

  3. 创建仅包含该节点片断的独立对象。

  4. 将该节点片断传递给 Transform 方法。

示例

以下示例转换节点片断并将结果输出到控制台。

// Load an XPathDocument.
XPathDocument doc = new XPathDocument("books.xml");

// Locate the node fragment.
XPathNavigator nav = doc.CreateNavigator();
XPathNavigator myBook = nav.SelectSingleNode("descendant::book[@ISBN = '0-201-63361-2']");

// Create a new object with just the node fragment.
XmlReader reader = myBook.ReadSubtree();
reader.MoveToContent();

// Load the style sheet.
XslCompiledTransform xslt = new XslCompiledTransform();
xslt.Load("single.xsl");

// Transform the node fragment.
xslt.Transform(reader, XmlWriter.Create(Console.Out, xslt.OutputSettings));
' Load an XPathDocument.
Dim doc As XPathDocument = New XPathDocument("books.xml")

' Locate the node fragment.
Dim nav As XPathNavigator = doc.CreateNavigator()
Dim myBook As XPathNavigator = nav.SelectSingleNode("descendant::book[@ISBN = '0-201-63361-2']")

' Create a new object with just the node fragment.
Dim reader As XmlReader = myBook.ReadSubtree()
reader.MoveToContent()

' Load the style sheet.
Dim xslt As XslCompiledTransform = New XslCompiledTransform()
xslt.Load("single.xsl")

' Transform the node fragment.
xslt.Transform(reader, XmlWriter.Create(Console.Out, xslt.OutputSettings))

输入

books.xml
<bookstore>
  <book genre="autobiography" publicationdate="1981" ISBN="1-861003-11-0">
    <title>The Autobiography of Benjamin Franklin</title>
    <author>
      <first-name>Benjamin</first-name>
      <last-name>Franklin</last-name>
    </author>
    <price>8.99</price>
  </book>
  <book genre="novel" publicationdate="1967" ISBN="0-201-63361-2">
    <title>The Confidence Man</title>
    <author>
      <first-name>Herman</first-name>
      <last-name>Melville</last-name>
    </author>
    <price>11.99</price>
  </book>
  <book genre="philosophy" publicationdate="1991" ISBN="1-861001-57-6">
    <title>The Gorgias</title>
    <author>
      <name>Plato</name>
    </author>
    <price>9.99</price>
  </book>
</bookstore>
single.xsl
<stylesheet version="1.0" xmlns="http://www.w3.org/1999/XSL/Transform" >
   <output method="text" /> 
   <template match="/">
      Book title is <value-of select="//title" /> 
   </template>
</stylesheet>

Output

书名为 The Confidence Man。

请参阅