Skip to content

XML with namespace and expression with attribute filter #1

@lazize

Description

@lazize

I don't know if I should open this issue here or on xpath, if it is wrong just let me know and I can close it here and open it there.

With the example below it demonstrate that expression like //node[@attr='value'] will not work when xml uses namespace and you are selecting a node that belongs to this namespace.

How can I make it work?

package main

import (
	"fmt"
	"os"
	"strings"

	"github.com/antchfx/xmlquery"
)

func main() {
	willWork()
	willFail()
}

func willWork() {
	fmt.Println("### WILL WORK")

	// Note: root node does not contain xmlns attribute
	xmlInput := `<root>
	  <myns:child id="1">value 1</myns:child>
	  <myns:child id="2">value 2</myns:child>
	</root>`

	reader := strings.NewReader(xmlInput)
	doc, err := xmlquery.Parse(reader)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	node := xmlquery.Find(doc, "//child[@id='1']")
	if node == nil {
		fmt.Println("ERROR - Not found")
	} else {
		fmt.Println("GOOD - Found")
		fmt.Println(len(node))
	}

	// Even though the expression above work, this one will fail
	node = xmlquery.Find(doc, "//myns:child[@id='1']")
	if node == nil {
		fmt.Println("ERROR - Not found")
	} else {
		fmt.Println("GOOD - Found")
		fmt.Println(len(node))
	}
}

func willFail() {
	fmt.Println("### WILL FAIL")

	// Note: root node contains xmlns attribute
	xmlInput := `<root xmlns:myns="bla bla bla">
	  <myns:child id="1">value 1</myns:child>
	  <myns:child id="2">value 2</myns:child>
	</root>`

	reader := strings.NewReader(xmlInput)
	doc, err := xmlquery.Parse(reader)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	node := xmlquery.Find(doc, "//child[@id='1']")
	if node == nil {
		fmt.Println("ERROR - Not found")
	} else {
		fmt.Println("GOOD - Found")
		fmt.Println(len(node))
	}

	node = xmlquery.Find(doc, "//myns:child[@id='1']")
	if node == nil {
		fmt.Println("ERROR - Not found")
	} else {
		fmt.Println("GOOD - Found")
		fmt.Println(len(node))
	}

	node = xmlquery.Find(doc, "//myns:child")
	if node == nil {
		fmt.Println("ERROR - Not found")
	} else {
		fmt.Println("GOOD - Found")
		fmt.Println(len(node))
	}
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions