【发布时间】:2016-05-02 17:54:33
【问题描述】:
我有//*[@id='test-id' and @some-other-attribute='some-value’] 类型的XPath 表达式。我想把它转换成//*[@resourceId='android:id/test-id' and @some-other-attribute='some-value’]。
我似乎找不到任何库函数来做到这一点。我不想求助于正则表达式查找和替换字符串 - 寻找一种结构化的方式来做到这一点。感谢任何指针。
注意:我不希望针对 XML 文件评估 XPath 表达式。我希望修改 XPath 表达式本身,而不使用字符串替换。
更新:
按照 kjhughes@ 的建议,我使用以下代码来获取 xpath 表达式的解析树。
Processor proc = new Processor(false);
XPathCompiler p = new XPathCompiler(proc);
XPathExecutable exec = p.compile("//*[@id='test-id' and @some-other-attribute='some-value']");
exec.getUnderlyingExpression().getInternalExpression().explain(new StandardLogger());
这会产生:
<filterExpression>
<slash simple-step="true">
<root/>
<axis name="descendant" nodeTest="element()"/>
</slash>
<operator op="and">
<operator op="=" cardinality="one-to-one">
<data>
<axis name="attribute" nodeTest="attribute(Q{}id)"/>
</data>
<literal value="test-id" type="xs:string"/>
</operator>
<operator op="=" cardinality="one-to-one">
<data>
<axis name="attribute" nodeTest="attribute(Q{}some-other-attribute)"/>
</data>
<literal value="some-value" type="xs:string"/>
</operator>
</operator>
</filterExpression>
解析 XML 节点并重新组合表达式是我唯一的选择吗?或者有没有我想念的更短的方法?
(我仍然需要弄清楚是否将 XML 转换回 Xpath 表达式是微不足道的,或者它是否会涉及任何诡计。)
【问题讨论】: