2013-06-06 139 views
0

我的来源是:查找元素

<content> 
    <caption>text 1</caption> 
    <element1>Notepad is a basic text-editing program and it's most commonly used to view or edit text files. A text <bold>file</bold> is a <a>file</a> type typically identified by the .txt file name extension.</element1> 
    <section1> 
    <element2>Notepad is a basic text-editing program and it's most commonly used to view or edit text files. A text file is a file type typically identified by the .txt file name extension.</element2> 
    </section1> 
</content> 

我试图提取并为元素打造独一无二的ID(它可以是任何元素),其中有两个孩子(字符元素)和文本,还有只有文本的元素。 <bold><a>元素不应该分开。

<caption id="id1">Text 1</caption> 
    <element1 id="id2">Notepad is a basic text-editing program and it's most commonly used to view or edit text files. A text <bold>file</bold> is a <a>file</a> type typically identified by the .txt file name extension.</element1> 
    <element2 id="id3">Notepad....</element2> 

任何想法,将不胜感激......

+0

你的输出格式是?你想跳过他们吗? –

+0

是的我想只提取包含字符串/字符串+子元素(字符)元素的元素。只有子元素但没有PCDATA的元素不需要考虑。 – VSr

+0

您的示例中的**标题**和** element2 **元素没有子元素,但仍具有id属性。这似乎与您说要从具有子项和文本的元素创建ID的位置相矛盾。它是否正确?谢谢! –

回答

0

我不太确定是否要保留层次还是你想输出你所描述的那些元素的平面列表;以下简单地提取所描述的元件为平的列表(尽管保持其内容),由XSLT处理器产生的id S:

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
    xmlns:xs="http://www.w3.org/2001/XMLSchema" 
    exclude-result-prefixes="xs"> 

<xsl:output indent="yes"/> 
<xsl:strip-space elements="*"/> 

<xsl:template match="*[not(*) and text()[normalize-space()]] | *[* and text()[normalize-space()]]"> 
    <xsl:copy> 
    <xsl:attribute name="id" select="generate-id()"/> 
    <xsl:apply-templates select="@* , node()" mode="copy"/> 
    </xsl:copy> 
</xsl:template> 

<xsl:template match="*" mode="copy"> 
    <xsl:copy> 
    <xsl:apply-templates select="@* , node()" mode="#current"/> 
    </xsl:copy> 
</xsl:template> 

</xsl:stylesheet> 

当施加到您的输入样本,撒克逊9个输出

<?xml version="1.0" encoding="UTF-8"?> 
<caption id="d1e2">text 1</caption> 
<element1 id="d1e4">Notepad is a basic text-editing program and it's most commonly used to view or edit text files. A text <bold>file</bold> is a <a>file</a> type typically identified by the .txt file name extension.</element1> 
<element2 id="d1e13">Notepad is a basic text-editing program and it's most commonly used to view or edit text files. A text file is a file type typically identified by the .txt file name extension.</element2> 
+0

Hi @Martin,谢谢你的代码。其实孩子元素不仅应该是大胆的,如何处理? – VSr

+0

请详细解释如何识别需要'id'属性的元素以及那些不需要属性的元素。我没有看到'bold'或'a'元素和'caption'元素(都带有纯文本内容)之间的区别,除了按名称区分它们。 –

+0

Hi @Martin。是的,你是对的。但在这种情况下,标题的父元素不具有PCDATA,因此它只包含子元素。这些元素可以被删除,并且该id应该包含在儿童中,即''。但''和''元素具有父元素,它具有PCDATA(字符串),所以在父元素中,id可以不包含在子元素中。 – VSr