如何区分从Saxon XPathSelector返回的属性和元素节点 [英] How to distinguish between attribute and element nodes returned from a Saxon XPathSelector

查看:124
本文介绍了如何区分从Saxon XPathSelector返回的属性和元素节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出XML:

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

我希望XPath /root/@name返回value,并且XPath /root/level1返回<level1>节点的XML序列化:

I want the XPath /root/@name to return value, and the XPath /root/level1 to return the XML serialisation of the <level1> node:

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

我正在使用Java中Saxon 9.6的a9api接口.

I'm using the a9api interface from Saxon 9.6 in Java.

我发现可以致电.而且我可以调用 以获得字符串值,该属性为我提供了正确的值,但返回了元素的文本内容.

I've found that I can call 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, which gets me the right value for the attribute, but returns the textual content of the element.

Michael Kay先前表示为"Saxon的s9api接口...返回其类型可以查询的XdmValue对象" .我可以看到可以执行instanceof检查来确定它是XdmAtomicValueXdmExternalObjectXdmFunctionItem还是XdmNode,但是元素和属性都是XdmNode的实例.如何区分两者?

Michael Kay has previously said "Saxon's s9api interface ... returns XdmValue objects whose type you can interrogate". I can see that I could perform an instanceof check to determine whether it is an XdmAtomicValue, XdmExternalObject, XdmFunctionItem, or XdmNode, but elements and attributes are both instances of XdmNode. How do I distinguish between the two?

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

(I can't modify the XPaths, as they're provided by the user.)

推荐答案

我在写完问题后才发现答案,所以我将其分享给其他人.

I discovered the answer just as I finished writing the question, so I'll share it for others.

XdmItem转换为XdmNode之后,可以调用

After casting the XdmItem to an XdmNode, you can call XdmNode.getNodeKind(), which returns a value from the XdmNodeKind enumeration specifying which type of node it is:

        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();

这篇关于如何区分从Saxon XPathSelector返回的属性和元素节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆