XSLT - XSLT and XPath
In XSLT and XPath, understanding node types is crucial because everything in XML is treated as a node.
1. Element Nodes
-
Definition: Represent XML tags (like
<book>
or<title>
). -
Can have:
-
Attributes
-
Text content
-
Child elements
-
-
Example:
<book>
<title>1984</title>
</book>
-
<book>
and<title>
are element nodes.
2. Attribute Nodes
-
Definition: Represent attributes inside elements.
-
Accessed in XPath using
@attributeName
. -
Example:
<book id="b1" genre="Fiction">
<title>1984</title>
</book>
-
id="b1"
andgenre="Fiction"
are attribute nodes. -
XPath example:
book/@id
→ selects"b1"
3. Text Nodes
-
Definition: Represent the text content inside elements.
-
Example:
<title>1984</title>
-
The
"1984"
part is a text node. -
In XPath,
text()
selects text nodes.
4. Namespace Nodes
-
Definition: Define XML namespaces (used to avoid element name conflicts).
-
Example:
<book xmlns:ns="http://example.com/ns">
<ns:title>1984</ns:title>
</book>
-
xmlns:ns
creates a namespace node. -
Often used in XPath with prefixes like
ns:title
.
5. Comment Nodes
-
Definition: XML comments inside
<!-- -->
. -
Example:
<!-- This is a comment -->
-
Selected with XPath
comment()
.
6. Processing Instruction Nodes
-
Definition: Special instructions for applications, not part of XML data.
-
Example:
<?xml-stylesheet type="text/xsl" href="style.xsl"?>
-
Selected with XPath
processing-instruction()
.
7. Document (Root) Node
-
Definition: The top-most node in the XML tree.
-
Every XML document has a single root node (
/
) that contains the root element. -
Example in XPath:
/
selects the root node.
Summary Table of Node Types
Node Type | Description | XPath Example |
---|---|---|
Element | XML tags | /library/book |
Attribute | Attributes inside elements | book/@id |
Text | Text inside elements | book/title/text() |
Namespace | Namespace declarations | namespace::* |
Comment | Comments | comment() |
Processing Instruction | Special instructions | processing-instruction() |
Document/Root | The root of the XML tree | / |
Key Point:
XSLT operates on these nodes, not raw text. Templates, match
, apply-templates
, and XPath all work by navigating and manipulating different node types.