2

入力XMLが任意であるXSLT変換を実行しようとしています。その中で一定している唯一のことは、名前が「first」で始まるノードを持つことです。そのノードの値を取得する必要があり、それは直接の兄弟です。ただし、次のテンプレートはXML宣言のみを生成します。

重要な場合、このコードはNokogiriXMLパーサーを使用するRubyにあります。ただし、これはRubyの質問ではなく、XSLT / XPathの質問であるため、それに応じてタグ付けされていると思います。

入力XML:

<?xml version="1.0"?>
<employees>
  <employee>
    <first_name>Winnie</first_name>
    <last_name>the Pooh</last_name>
  </employee>
  <employee>
    <first_name>Jamie</first_name>
    <last_name>the Weeh</last_name>
  </employee>
</employees>

必要な出力XML:

<?xml version="1.0"?>
<people>
  <person>
    <first>Winnie</first>
    <last>the Pooh</last>
  </person>
  <person>
    <first>Jamie</first>
    <last>the Weeh</last>
  </person>
</people>

XSLT:

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes" encoding="UTF-8" />
<xsl:template match="/">
  <xsl:for-each select="node()[starts-with(name(), 'first')]">
    <people>
      <person>
        <name>
      <first><xsl:value-of select="." /></first>
      <last><xsl:value-of select="following-sibling::*[1]" /></last>
    </name>
      </person>
    </people>
  </xsl:for-each>
</xsl:template>
  </xsl:stylesheet>
4

3 に答える 3

3
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes" encoding="UTF-8" />
  <!-- match the node that has a name starting with 'first' -->
  <xsl:template match="node()[starts-with(name(), 'first')]">
    <xsl:element name="people">
      <xsl:element name="person">
        <xsl:element name="name">
          <xsl:element name="first">
            <xsl:value-of select="." />
          </xsl:element>
          <xsl:element name="last">
            <xsl:value-of select="following-sibling::*[1]" />
          </xsl:element>
        </xsl:element>
      </xsl:element>
    </xsl:element>
    <xsl:apply-templates />
  </xsl:template>
  <!-- stop the processor walking the rest of the tree and hitting text nodes -->
  <xsl:template match="text()|@*" />
</xsl:stylesheet>
于 2013-02-23T20:39:28.763 に答える
3

入力XMLがあなたが提案するほど恣意的である場合、従業員/従業員を人/人に変更する方法がわかりません。ただし、次の方法でほぼ適切な効果を得ることができます。

<xsl:template match="*">
  <xsl:copy><xsl:apply-templates/></xsl:copy>
</xsl:template>

<xsl:template match="*[starts-with(name(), 'first')]">
  <first><xsl:apply-templates/></first>
</xsl:template>

<xsl:template match="*[preceding-sibling::*[1][starts-with(name(), 'first')]]">
  <last><xsl:apply-templates/></last>
</xsl:template>
于 2013-02-23T19:12:24.157 に答える
0

.//node()の代わりに使用してくださいnode()

于 2013-02-23T16:41:38.880 に答える