简体   繁体   English

使用Java和Xpath检查元素节点是否不包含文本?

[英]Check if element node contains no text using java and Xpath?

I am new to Xpath. 我是Xpath的新手。 I am facing a problem that I have to get a boolean response from Xpath, if an element does not contains any text then it should return false otherwise true. 我面临一个问题,我必须从Xpath获得布尔响应,如果一个元素不包含任何文本,则它应该返回false,否则返回true。 I have seen many examples and I don't have much time to learn Xpath expressions. 我已经看到了很多示例,而且我没有太多时间来学习Xpath表达式。 Below is the Xml file. 下面是Xml文件。

<?xml version="1.0" encoding="UTF-8" ?>
<order id="1234" date="05/06/2013">
  <customer first_name="James" last_name="Rorrison">
    <email>j.rorri@me.com</email>
    <phoneNumber>+44 1234 1234</phoneNumber>
  </customer>
  <content>
    <order_line item="H2G2" quantity="1">
      <unit_price>23.5</unit_price>
    </order_line>
    <order_line item="Harry Potter" quantity="2">
      <unit_price></unit_price>//**I want false here**
    </order_line>
  </content>
  <credit_card number="1357" expiry_date="10/13" control_number="234" type="Visa" />
</order>

Could you point me the right direction to create xpath expression for this problem. 您能否为我指出创建此问题的xpath表达式的正确方向。

What I want is a expression(dummy expression) as below. 我想要的是一个表达式(虚拟表达式),如下所示。

/order/content/order_line/unit_price[at this point I want to put a validation which will return true or false based on some check of isNull or notNull]. / order / content / order_line / unit_price [此刻,我想进行验证,该验证基于isNull或notNull的某些检查将返回true或false。

The following xpath will do this: 以下xpath将执行此操作:

not(boolean(//*[not(text() or *)]))

but this xpath will also include the credit_card node since it to does not contain any text (the attributes are not text()). 但此xpath也将包含credit_card节点,因为它的to不包含任何文本(属性不是text())。

if you also want to exclude node with attributes then use this.. 如果您还想排除具有属性的节点,则使用此属性。

not(boolean(//*[not(text() or * or @*)]))

Following your edit, you can do this.. 完成编辑后,您可以执行此操作。

/order/content/order_line/unit_price[not(text()]

It will return a list of nodes with no text and from there you can test against the count of nodes for your test. 它将返回没有文本的节点列表,您可以从那里对照要测试的节点数进行测试。

or to return true/false.. 或返回true / false。

not(boolean(/order/content/order_line/unit_price[not(text()]))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM