2016-05-13 13 views
2

私は、BaseXを使ってHTMLページを解析しようとしています。 コードのこの部分から:htmlリンクでテキストを抽出する方法は?

<td colspan="2" rowspan="1" class="light comment2 last2"> 
    <img class="textalign10" src="templates/comment10.png" 
     alt="*" width="10" height="10" border="0"/> 
    <a shape="rect" href="mypage.php?userid=26682">user</a> 
    : the text I'd like to keep [<a shape="rect" 
    href="http://alink" rel="nofollow">Link</a>] . with that part too. 
</td> 

私はa HTMLリンク、とメッセージを抽出し、初めに最初の:文字を削除する必要があります。

declare 
function gkm:node_message_from_comment($comment as item()*) { 
    if ($comment) then 
    copy $c := $comment 
    modify (
     delete node $c/img[1], 
     delete node $c/a[1], 
     delete node $c/@*, 
     rename node $c as 'message' 
    ) 
    return $c 
    else() 
}; 

が、私はテキストを抽出することができ、この機能を使用して

<message> 
the text I'd like to keep [<a shape="rect" href="http://alink" rel="nofollow">Link</a>] . with that part too. 
</message> 

、私は初めから:の削除に失敗しました:

私はこの正確なテキストを取得したいと思います。 すなわち:XQueryの更新と変換ステートメントを使用して

<message> 
: the text I'd like to keep [<a shape="rect" href="http://alink" rel="nofollow">Link</a>] . with that part too. 
</message> 

答えて

3

は私には少しovercomplicatedようです。 mypage.phpリンクに続くノードを選択することもできます。入力に関する知識が増えれば、必要なノードを選択するより良い方法があるかもしれません。

サブストリング:を切り取る場合は、substring-afterを使用してください。 「最初の結果ノードから:を切り捨て、他のものをそのまま返します」というパターンは、使用することを主張する場合、変換ステートメントを使用する場合にも適用できます。

let $comment :=<td colspan="2" rowspan="1" class="light comment2 last2"> 
    <img class="textalign10" src="templates/comment10.png" alt="*" width="10" height="10" border="0"/> 
    <a shape="rect" href="mypage.php?userid=26682">user</a> 
    : the text I'd like to keep [<a shape="rect" href="http://alink" rel="nofollow">Link</a>] . with that part too. 
</td> 
let $result := $comment/a[starts-with(@href, 'mypage.php')]/following-sibling::node() 
return <message>{ 
    $result[1]/substring-after(., ': '), 
    $result[position() > 1] 
}</message> 

BaseXは、XQuery 3.0をサポートしているため、あなたはまた、ヘルパー関数headtailの利点を取ることができる:

return <message>{ 
    head($result)/substring-after(., ': '), 
    tail($result) 
}</message> 
+0

は完璧に動作し、感謝を:) – KumZ

関連する問題