An open API service indexing awesome lists of open source software.

https://github.com/cxa/xpaver

Make XML navigation by XPath easier
https://github.com/cxa/xpaver

Last synced: about 1 year ago
JSON representation

Make XML navigation by XPath easier

Awesome Lists containing this project

README

          

# XPaver

Make XML navigation by XPath easier.

## Install

Swift package only. Add this repo url to your package dependencies. Xcode 11 supports by default.

## Usage

### Initialize a `Doc` first

```swift
let xmlDoc = try! Doc(fileURL: assetURL(forName: "xml.xml"), kind: .xml)
// or if you want to use on HTML
let htmlDoc = try! Doc(fileURL: assetURL(forName: "html.html"), kind: .html)
// you can also init from data or string
let dataDoc = try! Doc(data: #, kind: .xml)
let stringDoc = try! Doc(string: "Hello World", kind: .html)
```

### Navigate by XPath

```swift
// func select(xpath: String) -> [Node]
let nodes = htmlDoc.root.select(xpath: "//p") // Select all `p` on root node:

// func first(xpath: String) -> Node?
let p = htmlDoc.root.first(xpath: "//p") // Select first `p` on root node:
let span = p.first("./span") // Select first child span on `p`
```

### Evaluate XPath Expression

```swift
func eval(expr: String) -> Node.EvalResult?

// count how many p tags
let count = htmlDoc.root.eval(expr: "count(//p)")
```

### Node Info

```swift
var tag: String?
var content: String?
var rawContent: String?
var innerRawContent: String?
var attributes: AnySequence?
func value(forAttribute name: String) -> String?
```

### Node Hierarchies

```swift
var parent: Node?
var childNodes: AnySequence?
var firstNode: Node?
func childNode(at index: Int) -> Node?
var prev: Node?
var next: Node?
```

### Advanced usage on namespace

By default, `XPaver` will solve namespaces for you internally, you don't need to care namespaces if document has only one default namespace.

But if you encounter a XML which contains more than one namespace like this:

```xml

Rob
37

London
123.000
0.00

```

You need to register namespaces and write namespaces in XPath directly:

```swift
let mnsXmlDoc = try! Doc(fileURL: url, kind: .xml)
mnsXmlDoc.register(namespaceURI: "http://www.your.example.com/xml/person", forPrefix: "p")
mnsXmlDoc.register(namespaceURI: "http://www.my.example.com/xml/cities", forPrefix: "c")
let cityName = mnsXmlDoc.root.first(xpath: "/p:person/c:homecity/c:name")
```

## About Me

- Twitter: [@\_cxa](https://twitter.com/_cxa)
- Apps available on the App Store:
- PayPal: xianan.chen+paypal 📧 gmail.com, buy me a cup of coffee if you find this is useful for you

## LICENSE

MIT.