diff --git a/namespace_attributes_test.go b/namespace_attributes_test.go new file mode 100644 index 0000000..9d27cfc --- /dev/null +++ b/namespace_attributes_test.go @@ -0,0 +1,51 @@ +package xmlquery + +import ( + "sort" + "strings" + "testing" +) + +func TestXPathAttributeAxisExcludesNamespaceDeclarations(t *testing.T) { + doc, err := Parse(strings.NewReader(``)) + if err != nil { + t.Fatal(err) + } + nodes := Find(doc, `//*[local-name()='root']/@*`) + var names []string + for _, n := range nodes { + names = append(names, n.Prefix+":"+n.Data) + } + sort.Strings(names) + want := []string{":id", "p:code", "p:xmlns", "xml:lang"} + if len(names) != len(want) { + t.Fatalf("attribute names=%v want%v", names, want) + } + for i := range want { + if names[i] != want[i] { + t.Errorf("attribute names=%v want%v", names, want) + } + } + root := FindOne(doc, `//*[local-name()='root']`) + if root.SelectAttr("xmlns:p") != "urn:test" || len(root.Attr) != 6 { + t.Fatal("source namespace attributes were removed") + } + out := doc.OutputXML(false) + if !strings.Contains(out, `xmlns="urn:default"`) || !strings.Contains(out, `xmlns:p="urn:test"`) { + t.Fatalf("namespace declarations absent from serialized XML: %s", out) + } +} +func TestNamespaceOnlyElementHasNoXPathAttributes(t *testing.T) { + doc, err := Parse(strings.NewReader(``)) + if err != nil { + t.Fatal(err) + } + root := FindOne(doc, "//root") + nav := CreateXPathNavigator(root) + if nav.MoveToNextAttribute() { + t.Error("namespace declaration exposed as an attribute") + } + if nav.LocalName() != "root" { + t.Error("failed attribute move changed current node") + } +} diff --git a/query.go b/query.go index fd05108..2e018e5 100644 --- a/query.go +++ b/query.go @@ -234,11 +234,16 @@ func (x *NodeNavigator) MoveToParent() bool { } func (x *NodeNavigator) MoveToNextAttribute() bool { - if x.attr >= len(x.curr.Attr)-1 { - return false + for i := x.attr + 1; i < len(x.curr.Attr); i++ { + name := x.curr.Attr[i].Name + // xmlns declarations belong to the XPath namespace axis, not @*. + if name.Space == "xmlns" || (name.Space == "" && name.Local == "xmlns") { + continue + } + x.attr = i + return true } - x.attr++ - return true + return false } func (x *NodeNavigator) MoveToChild() bool {