如何区分从 Saxon XPathSelector 返回的属性节点和元素节点

How to distinguish between attribute and element nodes returned from a Saxon XPathSelector

鉴于 XML:

<root name="value">
  <level1>
    <level2>Text</level2>
  </level1>
</root>

我希望 XPath /root/@name 到 return value,以及 XPath /root/level1 到 return 的 XML 序列化 <level1>节点:

  <level1>
    <level2>Text</level2>
  </level1>

我在 Java 中使用来自 Saxon 9.6 的 a9api 接口。

我发现我可以调用 XdmValue.toString() to get the XML serialisation of the result of the evaluation of the XPath, which gets me the desired result for selecting an element, but returns name="value" when selecting an attribute. And I can call XdmItem.getStringValue() to get the string value,它为我提供了正确的属性值,但 return 是元素的文本内容。

Michael Kay 之前 said "Saxon's s9api interface ... returns XdmValue objects whose type you can interrogate"。我可以看到我可以执行 instanceof 检查以确定它是 XdmAtomicValueXdmExternalObjectXdmFunctionItem 还是 XdmNode,但是元素和属性是XdmNode 的两个实例。如何区分两者?

(我无法修改 XPath,因为它们是由用户提供的。)

我刚写完题就发现了答案,所以我会分享给其他人。

XdmItem 转换为 XdmNode 后,您可以调用 XdmNode.getNodeKind(), which returns a value from the XdmNodeKind 枚举指定它是哪种类型的节点:

        XdmValue matchList = xPathSelector.evaluate();
        XdmItem firstItem = matchList.itemAt(0);
        if (firstItem instanceof XdmNode) {
           XdmNode xdmNode = (XdmNode) firstItem;
           XdmNodeKind nodeKind = xdmNode.getNodeKind();
           if (nodeKind == XdmNodeKind.ELEMENT) {
              return xdmNode.toString();
           }
        }
        return firstItem.getStringValue();