如何区分从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
返回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
检查来确定它是XdmAtomicValue
,XdmExternalObject
,XdmFunctionItem
还是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
之后,可以调用 XdmNodeKind
枚举,指定它是哪种节点类型:
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屋!