Search code examples
xmlgoetreepackage

How does the Go etree XML package define "siblings" and "children"?


I have an XML struct like this.

<Process>
     <Name> Process1 </Name>
     <SQLFile> aSQLFile.sql </SQLFile>
     <SQLText> select * from Items <SQLText>
     <Mode> 2 </Mode>
<Process>

I am using beevik/etree to work with this.

In the sample code below, a list of this XML struct is called elems. I am calling this code to walk through elems in an XML document:

for elemA := range elems.FindElements("//Name") {
    elemB:=elemA.FindElement(//SQLFile){
       doSomething(elemB)
}

This code works - doSomething(elemB) does what it is supposed to do, but according to the etree comments on FindElement, it should fail. elemB should be nil:

FindElement returns the first element matched by the XPath-like 'path' string. The function returns nil if no child element is found using the path.

According to that comment, elemB:=elemA.FindElement(//SQLFile) should return nil, because <SQLFile> is a sibling of <Name>, not a child. <Name> has no child.

Why isn't elemA.FindElement(//SQLFile) returning nil in this code?


Solution

  • The etree comments are not quite clear here, and I misuderstood them.

    The function returns nil if no child element is found using the // path. is a misreading. // returns a sibling, not a child, as the XPath would indicate. But // is part of the comment, not the XPath code itself as indicated by the space before path.

    .

    .//returns a child only.

    (Thanks to @kostix for pointing me in the right direction in the comments on the question.)