-1

I was wondering there was a way for XPath to return HTML of a particular element?

<td>
1212 S.W. 123 St.
<br>
Flower, Maryland 11234
<br>
United States
</td>

XPath query:

string(//table[@cellspacing='10']/tr[2]/td[2])

Current Output

1212 S.W. 123 St.Flower, Maryland 11234United States

Desired output:

1212 S.W. 123 St.<br>Flower, Maryland 11234<br>United States

AnchovyLegend
  • 12,139
  • 38
  • 147
  • 231
  • Please provide reference that demonstrate how xpath should be able - by it's specification - to return a string of such a kind. Unless you do I'm free to cv against a duplicate for domdocument concerning what you *try* to do. – hakre Jul 03 '13 at 05:11

2 Answers2

2

You are asking for a string, so you are getting a string. If you just want nodes, just address the children nodes of the table data element:

  table[@cellspacing='10']/tr[2]/td[2]/node()

... and you will get text and element nodes.

If you are using XSLT, don't use <xsl:value-of> because that also gives you a string, use <xsl:copy-of> to get the nodes. Though I suspect you aren't using XSLT because you can't input HTML into an XSLT process.

G. Ken Holman
  • 4,333
  • 16
  • 14
  • Thanks for the reply. This method did not work for me. The results returned are the same as if I removed the `string()` call from the xPath query in the original post. I am trying to get the inner HTML... I am using PHP and also have access to google docs `importXML()`. – AnchovyLegend Jun 29 '13 at 21:44
  • Then I can't help you, sorry. I know the XPath address I gave you addresses the nodes, so the language using XPath needs to act on the nodes, not the string. I am unfamiliar with the use of `importXML()` in PHP. I hope someone else can help you. – G. Ken Holman Jun 29 '13 at 23:49
0

This is less of an XPath problem and more of a PHP problem. You don't really say what you are using to run your XPath, but I'll assume DOM since you are parsing HTML.

Below is the code that you'll need to get the inner contents of your elements. Note, that once you find the node, you need to call nodeValue to get everything underneath it.

<?php

$html = <<<HTML
<table>
    <tr>
        <td>
            1212 S.W. 123 St.
            <br>
            Flower, Maryland 11234
            <br>
            United States
        </td>
    <tr>
</table>
HTML;
$dom = new DOMDocument;
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$nodes = $xpath->query('//table/tr/td');

foreach($nodes as $node) {
    echo $node->nodeValue;
}

?>