0
votes

I want to get only elements in my XML file that contains only one attribute using XPath.

This is the XML File :

<?xml version="1.0" encoding="UTF-8"?>
<livre titre="Mon livre">
    <auteurs>
        <auteur nom="nom1" prenom="prenom1" />
        <auteur nom="nom2" prenom="prenom2" />
    </auteurs>
    <sections>
        <section titre="Section1">
            <chapitre titre="Chapitre1">
                <paragraphe>Premier paragraphe</paragraphe>
                <paragraphe>Deuxième paragraphe</paragraphe>
            </chapitre>
            <chapitre titre="Chapitre2">
                <paragraphe>Premier paragraphe</paragraphe>
            </chapitre>
        </section>
        <section titre="section2">
            <chapitre titre="Chapitre1">
                <paragraphe>Premier paragraphe</paragraphe>
                <paragraphe>Deuxième paragraphe</paragraphe>
            </chapitre>
        </section>
    </sections>
</livre>

This is what I tried to do :

/descendant-or-self::node()[count(self::node()/attribute::node()) = 1]

But it didn't work.

But The XPath query I wrote select all elements which contains more than one attribute, and I only want to select elements that contains only one attribute.

The result of the XPath query should be like this :

Description: titre="Mon livre"
XPath location: /livre[1]
Start location: 2:1
End location: 20:9

Description: titre="Section1"
XPath location: /livre[1]/sections[1]/section[1]
Start location: 8:5
End location: 16:19

Description: titre="Chapitre1"
XPath location: /livre[1]/sections[1]/section[1]/chapitre[1]
Start location: 9:13
End location: 12:24

Description: titre="Chapitre2"
XPath location: /livre[1]/sections[1]/section[1]/chapitre[2]
Start location: 13:13
End location: 15:24

Description: titre="section2"
XPath location: /livre[1]/sections[1]/section[2]
Start location: 17:9
End location: 18:19

How can I do that ?

1

1 Answers

3
votes

This should work:

//*[count(@*)=1]

p.s., I get 6 items, for that data, there is another chapitre under section2.