使用XPath从选择性元素中查找属性

时间:2014-03-31 21:14:13

标签: xml xpath

我有以下XMl:

<bookstore specialty="novel">
    <book style="autobiography">
        <title>Seven Years in Trenton</title>
        <author>
            <first-name>Joe</first-name>
            <last-name>Bob</last-name>
        </author>
        <award>Trenton Literary Review Honorable Mention</award>
        <price>12</price>
    </book>
    <book style="textbook">
        <title>History of Trenton</title>
        <author>
            <first-name>Mary</first-name>
            <last-name>Bob</last-name>
        </author>
        <price type="regular">55</price>
        <price type="sale">45</price>
    </book>
    <magazine style="glossy" frequency="monthly">
        <title>Tracking Trenton</title>
        <price>2.50</price>
        <subscription price="24" per="year"/>
    </magazine>
    <Textbook style="Science" id="myfave">
        <title>Trenton Today, Trenton Tomorrow</title>
        <author>
            <first-name>Toni</first-name>
            <last-name>Bob</last-name>
            <degree from="Trenton U">B.A.</degree>
            <degree from="Harvard">Ph.D.</degree>
            <award>Pulitzer</award>
        </author>
        <price intl="canada" exchange="0.7">6.50</price>
        <excerpt>
            It was a dark and stormy night.But then all nights in Trenton seem dark and stormy to someone who has gone through what can only be defined as Trenton misery
        </excerpt>
    </Textbook>
</bookstore>

使用XPath我需要找到元素类型Book and Magazine但不是Textbook的所有样式属性。我遇到了这个问题,因为我无法弄清楚如何将3个元素分开,因为它们都处于同一级别。有什么帮助吗?

3 个答案:

答案 0 :(得分:1)

使用通配符*选择bookstore的所有子元素。

使用过滤器[not(name()='Textbook')]来区分您感兴趣的元素。

最后:

/bookstore/*[not(name()='Textbook')]/@style

答案 1 :(得分:1)

更好的方法可能是:

/bookstore/*[name()='book' or name()='magazine']/@style

答案 2 :(得分:1)

我使用self::代替name() ...

/bookstore/*[not(self::Textbook)]/@style

如果我检查magazinebook,我也会这样做......

/bookstore/*[self::magazine or self::book]/@style

您也可以使用name()(XPath 2.0)...

的序列
/bookstore/*[name()=('magazine','book')]/@style