<!--
{
  "availability" : [
    "macCatalyst: 13.0.0 -",
    "macOS: 10.0.0 -"
  ],
  "documentType" : "symbol",
  "framework" : "Foundation",
  "identifier" : "/documentation/Foundation/XMLNode/nodes(forXPath:)",
  "metadataVersion" : "0.1.0",
  "role" : "Instance Method",
  "symbol" : {
    "kind" : "Instance Method",
    "modules" : [
      "Foundation"
    ],
    "preciseIdentifier" : "c:objc(cs)NSXMLNode(im)nodesForXPath:error:"
  },
  "title" : "nodes(forXPath:)"
}
-->

# nodes(forXPath:)

Returns the nodes resulting from executing an XPath query upon the receiver.

```
func nodes(forXPath xpath: String) throws -> [XMLNode]
```

## Parameters

`xpath`

A string that expresses an XPath query.

## Return Value

An array of `NSXMLNode` objects that match the query, or an empty array if there are no matches.

## Discussion

The receiver acts as the context item for the query (”.”).  If you have explicitly added adjacent text nodes as children of an element, you should invoke the `NSXMLElement` method [`normalizeAdjacentTextNodesPreservingCDATA(_:)`](/documentation/Foundation/XMLElement/normalizeAdjacentTextNodesPreservingCDATA(_:)) (with an argument of <doc://com.apple.documentation/documentation/Swift/false>) on the element before applying any XPath queries to it; this method coalesces these text nodes. The same precaution applies if you have processed a document preserving CDATA sections and these sections are adjacent to text nodes.

> Handling Errors in Swift:
> In Swift, this method returns a nonoptional result and is marked with the `throws` keyword to indicate that it throws an error in cases of failure.
> 
> You call this method in a `try` expression and handle any errors in the `catch` clauses of a `do` statement, as described in [Error Handling](https://docs.swift.org/swift-book/LanguageGuide/ErrorHandling.html) in [The Swift Programming Language](https://docs.swift.org/swift-book/) and `About Imported Cocoa Error Parameters`.

---

Copyright &copy; 2026 Apple Inc. All rights reserved. | [Terms of Use](https://www.apple.com/legal/internet-services/terms/site.html) | [Privacy Policy](https://www.apple.com/privacy/privacy-policy)