Martin Eve
Martin Eve

Reputation: 2751

Select all siblings (including text) of comment in xpath

I have an XML document, a fragment line of which could look like this:

<p>Some text <!--a comment --> some more text <b>some bold text</b> something else etc</p>

I would like to select the comment based on its text, but also all following "sibling" elements. In this example, I know I can get the comment with '//comment()[. = "a comment"]'.

How can I get the result: " some more text some bold text something else etc"? (the remainder of the siblings inside the paragraph tag)

In case it makes any difference, I'm using python and etree to parse.

EDIT:

My test XML in full:

<?xml version="1.0" encoding="UTF-8"?>
<root>
<p>A paragraph<!--A comment--><b>test</b>A line break</p>
</root>

My test XSLT:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="1.0">
    <xsl:template match="/">
        <xsl:copy-of select='//comment()/following-sibling::node()'/>
    </xsl:template>
</xsl:stylesheet>

The result:

<?xml version="1.0" encoding="UTF-8"?>

or, in Python, using lxml, just a "None" object.

EDIT #2:

My bad -- the accepted answer works well!

Upvotes: 1

Views: 924

Answers (1)

Jake Cobb
Jake Cobb

Reputation: 1861

If you want to get all siblings including other comments:

//comment()[.="a comment "]/following-sibling::node()

For example:

>>> xml.xpath('//comment()[.="a comment "]/following-sibling::node()')
[' some more text ', <Element b at 0x2923af0>, ' ', <!-- other comment -->, ' something else etc']

I added an additional comment but otherwise used your input data.

Upvotes: 1

Related Questions