简体   繁体   English

如何在JAVA中获取XPath查询结果的父节点

[英]How to getting parent node of XPath query result in JAVA

I use javax.xml.parsers.DocumentBuilder in the java. 我在Java中使用javax.xml.parsers.DocumentBuilder。 Given markup like this: 给定这样的标记:

 <?xml version="1.0" encoding="utf-8"?>
    <calendar>
        <endfiscalyear month="12" dayofmonth="28" />
        <year yr="2014">
          <event month="12" dayofmonth="24">
            <p>Dividendenauszahlung</p>
            <en>dividend payment</en>
          </event>
        </year>
        <year yr="2015">
          <event month="2" dayofmonth="1">
            <p>Hauptversammlung</p>
            <en>general meeting</en>
          </event>
           <event month="5" dayofmonth="2">
            <p>Hauptversammlung</p>
            <en>general meeting</en>
          </event>
          <event month="8" dayofmonth="21">
            <p>Ergebnis 2.Quartal</p>
            <en>1st quarter results</en>
          </event>
        </year>
      </calendar>

Now I am interested in getting the last year and month and dayofmonth only, where the last is 'general meeting', in this mask it should be year@yr=2015, <event month="4" dayofmonth="21"> . 现在,我感兴趣的是仅获取最后的年份,月份和日期,最后一个是“一般会议”,在此掩码中,应该为year @ yr = 2015, <event month="4" dayofmonth="21"> I can get the year, month and day separately, but as i tried, none of them get shown. 我可以分别获取年,月和日,但是正如我尝试过的,没有一个显示出来。 first l'd like any year: the two ways that i tried are: 首先,我想要任何一年:我尝试过的两种方法是:

//*@yr[event/en='general meeting']   

or 要么

/calendar/year[event/en='general meeting']@yr 

but none of them are correct. 但它们都不对。 How would you like to solve the problem? 您想如何解决这个问题?

It is unclear what you are asking, but sometimes it is easier to comment on an attempted solution than trying to explain. 目前尚不清楚您要问什么,但有时对尝试的解决方案发表评论要比尝试解释要容易。

The following XPath expression is valid: 以下XPath表达式有效:

/calendar/year[event/en='general meeting']/@yr

and here is what it does: 这是它的作用:

Select year elements, but only if they have a child element event , which in turn has a child element en , whose textual content is "general meeting". 选择year元素,但前提是它们具有子元素event ,而子元素event又具有子元素en ,其文本内容为“一般会议”。 Of those year elements select the attribute yr . 在这些year元素中,选择属性yr

For the input document you show, only one such attribute would qualify, and therefore the output would be 对于您显示的输入文档,只有一个这样的属性符合条件,因此输出为

 yr="2015"

Is this what you had in mind? 这就是您的想法吗? If not, please show (instead of trying to explain) the output you expect from an expression - and explain why this result should be selected. 如果不是,请显示 (而不是试图解释)您希望从表达式获得的输出-并说明为什么应选择此结果。

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

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