共用方式為


作法:轉換節點片段

當您轉換包含於 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>

輸出

書名為《The Confidence Man》。

另請參閱