Как получить доступ к текстовым значениям из нескольких дочерних узлов?Только получение значений из первого экземпляра дочернего узла - PullRequest
1 голос
/ 23 июня 2011

Я унаследовал довольно уродливый сценарий xsl и очень ограниченный опыт работы с xslt.Вчера мне очень помогли вы, ребята, но все еще немного боретесь, поэтому я предоставляю весь XML и лучшее описание желаемого результата.

Я полагаю, что сделать что-то глупое, заключив весь скрипт в шаблони выбор, потому что я продолжаю получать ошибки компиляции, когда я делаю предлагаемые изменения, и потому что я немного летаю вслепую, мне ясно, что у меня недостаточно понимания и времени, чтобы приобрести его, поэтому я искренне благодарен за некоторую помощь.На данном этапе меня интересует только компонент 4 .Я уверен, что, как только я это сделаю, я смогу переписать остальную часть сценария.

Вывод, который я получаю;

contactID,mediumCode,areaCode,communicationDetails
"0123456789","T","02","62881111"
"5290001890","T","02","92881781"
"4400139361","T","07","49281771"
"6600027368","T","07","48103280"

Вывод, который мне нужен;

contactID,mediumCode,areaCode,communicationDetails
"0123456789","T","02","62881111"
"5290001890","T","02","92881781"
"4400139361","T","07","49281771"
"6600027368","T","07","48103280"

"0123456789","E","","john.smith@myisp.com.au"
"5290001890","E","","rabina.smiley@ekit.com.au"
"4400139361","E","","suzanne.jones2@optus.com"
"6600027368","E","","maryann.smart@dodo.com"

"0123456789","M","","04140012225"
"5290001890","M","","04290012333"
"4400139361","M","","0404009266"
"6600027368","M","","0414003242"

Таблица стилей XSL:

<!-- AHPRA XML CSV Converter Script -->
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="text" media-type="text" encoding="UTF-8" indent="no" />
<xsl:strip-space elements="*" />

<!-- BATCH FILE COMPONENT -->
<xsl:param name="component"/>
<!-- 0=requestHeader, 1=personalDetails, 2=residencyDetails, 3=addressDetails, 4=communications, 5=primaryQualification, 6=additionalQualifications, 7=legacyDetails, 8=registrationDetails, 9=specialtyDetails, 10=conditionDetails, 11=endorsementDetails, 12=undertakingDetails, 13=notationDetails, 14=employmentDetails -->

<!-- FORMAT DATE -->
<xsl:template name="formatDate">
  <xsl:param name="date"/>
  <xsl:choose>
    <xsl:when test="boolean($date)">
      <xsl:if test="string-length($date)&gt;0">
        <xsl:value-of select="concat(substring($date,9,2),'/',substring($date,6,2),'/',substring($date,1,4))" />
      </xsl:if>
    </xsl:when>
    <xsl:otherwise> </xsl:otherwise>
  </xsl:choose>
</xsl:template>

<!-- NL2BR -->
<xsl:template name="nl2br">
  <xsl:param name="string"/>
  <xsl:choose>
    <xsl:when test="contains($string,'&#10;')">
      <xsl:value-of select="substring-before($string, '&#10;')" disable-output-escaping="yes"/>
      <br/>
      <xsl:call-template name="nl2br"><xsl:with-param name="string" select="substring-after($string,'&#10;')"/></xsl:call-template>
    </xsl:when>
   <xsl:otherwise>
     <xsl:value-of select="$string" disable-output-escaping="yes"/>
   </xsl:otherwise>
  </xsl:choose>
</xsl:template>

<xsl:template match="/">
  <xsl:choose>

    <!-- COMPONENT 0 requestHeader -->
    <!-- runType, dateStamp, sequenceNumber -->
    <xsl:when test="$component=0">
      <xsl:for-each select="medicare">
        "<xsl:value-of select="requestHeader/runType" />",
        <xsl:call-template name="formatDate">
          <xsl:with-param name="date" select="requestHeader/dateStamp"/>
        </xsl:call-template>,
        "<xsl:value-of select="requestHeader/sequenceNumber" />
        "<xsl:text>&#xa;</xsl:text>
      </xsl:for-each>
    </xsl:when>

    <!-- COMPONENT 1 personalDetails -->
    <!-- contactID, givenName, middleName, familyName, title, gender, dateOfBirth, dobAccuracy, dateOfDeath -->
    <xsl:when test="$component=1">
      <xsl:for-each select="//person">
        <xsl:if test="string-length(concat(personalDetails/givenName,personalDetails/middleName,personalDetails/familyName,personalDetails/title,personalDetails/gender,personalDetails/dateOfBirth,personalDetails/dobAccuracy,personalDetails/dateOfDeath))!=0">
          "<xsl:value-of select="contactID" />",
          "<xsl:value-of select="personalDetails/givenName" />",
          "<xsl:value-of select="personalDetails/middleName" />",
          "<xsl:value-of select="personalDetails/familyName" />",
          "<xsl:value-of select="personalDetails/title" />",
          "<xsl:value-of select="personalDetails/gender" />",
          <xsl:call-template name="formatDate"><xsl:with-param name="date" select="personalDetails/dateOfBirth"/></xsl:call-template>,
          "<xsl:value-of select="personalDetails/dobAccuracy" />",
          <xsl:call-template name="formatDate"><xsl:with-param name="date" select="personalDetails/dateOfDeath"/>
          </xsl:call-template>
          <xsl:text>&#xa;</xsl:text>
        </xsl:if>
      </xsl:for-each>
    </xsl:when>

    <!-- COMPONENT 4 communications -->
    <!-- contactID, mediumCode, areaCode, communicationDetails -->

    <xsl:variable name="q" select="'&quot;'" />
    <xsl:variable name="c" select="', '" />

    <xsl:when test="$component=4">
      <xsl:for-each select="//person">
        <xsl:if test="string-length(concat(communications/communication/mediumCode,communications/communication/areaCode,communications/communication/communicationDetails))!=0">
          <xsl:value-of select="concat($q, contactID, $q, $c, $q, 
          normalize-space(communications/communication/mediumCode), $q, $c, $q, 
          normalize-space(communications/communication/areaCode), $q, $c, $q, 
          normalize-space(communications/communication/communicationDetails), $q)" />
          <xsl:text>&#xa;</xsl:text>
        </xsl:if>
      </xsl:for-each>
    </xsl:when>

    </xsl:choose>
  </xsl:template>
</xsl:stylesheet>

Данные XML:

<medicare>  
  <requestHeader>
    <runType>O</runType>
    <dateStamp>2011-05-30</dateStamp>
    <sequenceNumber>10</sequenceNumber>
  </requestHeader>
  <person>
    <contactID>0123456789</contactID>
    <personalDetails>
      <givenName>John</givenName>
      <middleName>Alan</middleName>
      <familyName>Smith</familyName>
      <title>DR</title>
      <gender>M</gender>
      <dateOfBirth>1932-03-10</dateOfBirth>      
      <dobAccuracy>AAA</dobAccuracy>
      <dateOfDeath>1932-03-11</dateOfDeath>
    </personalDetails>
    <residencyDetails>
      <residencyStatus>Permanent Resident</residencyStatus>
      <visaType>Temporary</visaType>
      <passportNum>F1925190</passportNum>
      <countryOfIssue>Australia</countryOfIssue>
    </residencyDetails>
    <addressDetails>
      <address>
      <addressPurposeIndicator>Preferred Address</addressPurposeIndicator>
      <floorLevelNum>10</floorLevelNum>
    <floorLevelType>Ground</floorLevelType>
    <lotNum>72</lotNum>
        <postcode>2000</postcode>
        <state>NSW</state>
        <streetName>Main</streetName>
        <streetNum>112</streetNum>
        <streetType>RD</streetType>
        <locality>SYDNEY</locality>
        <flatUnitNum>3</flatUnitNum>
    <flatUnitType>Unit</flatUnitType>
        <sitePremisesName>St Vincents</sitePremisesName>
      </address>
      <address>
        <addressPurposeIndicator>Principle Place of Practice</addressPurposeIndicator>
        <floorLevelNum />
    <floorLevelType />
    <lotNum />
        <postcode>2000</postcode>
        <state>NSW</state>
        <streetName>Station</streetName>
        <streetNum />
        <streetType>ST</streetType>
        <locality>SYDNEY</locality>
        <flatUnitNum />
    <flatUnitType />
        <sitePremisesName>North Shore Hospital</sitePremisesName>
      </address>
    </addressDetails>
    <communications>
      <communication>
        <mediumCode>T</mediumCode>
      <areaCode>02</areaCode>
        <communicationDetails>62881111</communicationDetails>
      </communication>
      <communication>
        <mediumCode>E</mediumCode>
        <communicationDetails>john.smith@myisp.com.au</communicationDetails>
      </communication>
    <communication>
        <mediumCode>M</mediumCode>
        <communicationDetails>04140012225</communicationDetails>
      </communication>
    </communications>
    <registrationDetails>
       <registration>
          <registrationID>MED0000000009</registrationID>
          <profession>Medical Practitioner</profession>
          <division />
          <initialRegistrationStartDate>1977-08-03</initialRegistrationStartDate>
          <registrationType>General</registrationType>
          <registrationSubType />
          <registrationTypeStartDate>2011-04-30</registrationTypeStartDate>
          <registrationStatus>Registered</registrationStatus>
          <registrationStatusStartDate>2011-05-30</registrationStatusStartDate>
          <specialtyDetails>
            <specialtyDetail>
               <specialty>Heart Bypass</specialty>
               <fieldOfSpecialtyPractice>Surgery</fieldOfSpecialtyPractice>
           <specialtyPracticeStartDate>2010-02-20</specialtyPracticeStartDate>
           <specialtyPracticeEndDate>2011-04-23</specialtyPracticeEndDate>
            </specialtyDetail>
          </specialtyDetails>
          <conditionDetails>
            <condition>
               <applicationRegistrationCondition>APPROVED</applicationRegistrationCondition>
               <conditionApprovedDate>1805-12-08</conditionApprovedDate>
               <conditionDetail>The quick brown fox jumped over the lazy dog.</conditionDetail>
            </condition>
        </conditionDetails>
        <endorsementDetails>
          <endorsement>
               <endorsementType>Medicine Man</endorsementType>
               <endorsementSubType>Voodoo</endorsementSubType>
               <endorsementCreateDate>2002-08-20</endorsementCreateDate>
               <endorsementEndDate>2017-06-06</endorsementEndDate>
          </endorsement>
        </endorsementDetails>
        <undertakingDetails>
          <undertaking>
               <undertakingType>Further Study</undertakingType>
               <undertakingApprovedDate>2001-07-11</undertakingApprovedDate>
               <undertakingText>The Doctor will undertake further study.</undertakingText>
          </undertaking>
        </undertakingDetails>
          <notationDetails>
            <notationDetail>
               <notationCreateDate />  
               <notationEndDate />  
           <notation />
            </notationDetail>
          </notationDetails>
        </registration>
        <registration>
          <registrationID>MED0000000010</registrationID>
          <profession>Medical Practitioner</profession>
          <division />
          <initialRegistrationStartDate>1977-08-03</initialRegistrationStartDate>
          <registrationType>Specialist</registrationType>
          <registrationSubType />
          <registrationTypeStartDate>2011-04-30</registrationTypeStartDate>
          <registrationStatus>Registered</registrationStatus>
          <registrationStatusStartDate>2011-05-30</registrationStatusStartDate>
          <specialtyDetails>
            <specialtyDetail>
               <specialty>Pathology</specialty>
               <fieldOfSpecialtyPractice>General pathology</fieldOfSpecialtyPractice>
           <specialtyPracticeStartDate>2010-11-01</specialtyPracticeStartDate>
           <specialtyPracticeEndDate />
            </specialtyDetail>
          </specialtyDetails>
          <conditionDetails>
            <condition>
               <applicationRegistrationCondition>APPROVED</applicationRegistrationCondition>
               <conditionApprovedDate>1805-12-08</conditionApprovedDate>
               <conditionDetail>The quick brown fox jumped over the lazy dog.</conditionDetail>
            </condition>
        </conditionDetails>
        <endorsementDetails>
          <endorsement>
               <endorsementType />
               <endorsementSubType />
               <endorsementCreateDate />
               <endorsementEndDate />
          </endorsement>
        </endorsementDetails>
        <undertakingDetails>
          <undertaking>
               <undertakingType></undertakingType>
               <undertakingApprovedDate></undertakingApprovedDate>
               <undertakingText></undertakingText>
          </undertaking>
        </undertakingDetails>
          <notationDetails>
            <notationDetail>
               <notationCreateDate />  
               <notationEndDate />  
           <notation />
            </notationDetail>
          </notationDetails>
       </registration>
    </registrationDetails>
    <employmentDetails>
      <positionTitle>Chief Medical Officer</positionTitle>
      <sponsorOrganisationName>North Shore Hospital</sponsorOrganisationName>
      <sponsorOrganisationContact>Peter Piper</sponsorOrganisationContact>
    </employmentDetails>
  </person>
  <person>
    <contactID>5290001890</contactID>
    <personalDetails>
      <givenName>Rabina</givenName>
      <middleName>Dora</middleName>
      <familyName>Smiley</familyName>
      <title>DR</title>
      <gender>F</gender>
      <dateOfBirth>1961-03-22</dateOfBirth>      
      <dobAccuracy>AAA</dobAccuracy>
      <dateOfDeath>1900-12-01</dateOfDeath>
    </personalDetails>
    <residencyDetails>
      <residencyStatus>Australian Citizen</residencyStatus>
      <visaType>Perm</visaType>
      <passportNum>P1234567</passportNum>
      <countryOfIssue>New Zealand</countryOfIssue>
    </residencyDetails>
    <addressDetails>
      <address>
        <addressPurposeIndicator>Both preferred and practice</addressPurposeIndicator>
        <floorLevelNum />
      <floorLevelType />
      <lotNum />
        <postcode>2040</postcode>
        <state>NSW</state>
        <streetName>Plenty</streetName>
        <streetNum>29</streetNum>
        <streetType>RD</streetType>
        <locality>LEICHHARDT</locality>
        <flatUnitNum />
      <flatUnitType />
        <sitePremisesName />
      </address>
    </addressDetails>
    <communications>
      <communication>
        <mediumCode>T</mediumCode>
      <areaCode>02</areaCode>
        <communicationDetails>92881781</communicationDetails>
      </communication>
      <communication>
        <mediumCode>E</mediumCode>
        <communicationDetails>rabina.smiley@ekit.com</communicationDetails>
      </communication>
    <communication>
        <mediumCode>M</mediumCode>
        <communicationDetails>04290012333</communicationDetails>
      </communication>
    </communications>
    <registrationDetails>
       <registration>
          <registrationID>MED0000000219</registrationID>
          <profession>Medical Practitioner</profession>
          <division />
          <initialRegistrationStartDate>2010-04-15</initialRegistrationStartDate>
          <registrationType>Limited</registrationType>
          <registrationSubType>Area of Need</registrationSubType>
          <registrationTypeStartDate>2010-05-20</registrationTypeStartDate>
          <registrationStatus>Surrendered</registrationStatus>
          <registrationStatusStartDate>2011-05-29</registrationStatusStartDate>
          <specialtyDetails>
            <specialtyDetail>
               <specialty>Delivering Babies</specialty>
               <fieldOfSpecialtyPractice>Midwifery</fieldOfSpecialtyPractice>
           <specialtyPracticeStartDate>2009-01-31</specialtyPracticeStartDate>
           <specialtyPracticeEndDate>2099-04-08</specialtyPracticeEndDate>
            </specialtyDetail>
          </specialtyDetails>
          <conditionDetails>
            <condition>
               <applicationRegistrationCondition>Area of Need</applicationRegistrationCondition>
               <conditionApprovedDate>2010-05-28</conditionApprovedDate>
               <conditionDetail>PRE AMC TRAINING - TO WORK WITHIN EMERGENCY AT LYELL MCEWIN HOSPITAL - UNDER SUPERVISION OF DR H BLAH, DR B BLOGS NOMINATED SUPERVISORS.</conditionDetail>
            </condition>
           <condition>
               <applicationRegistrationCondition>Area of Need</applicationRegistrationCondition>
               <conditionApprovedDate>2011-05-22</conditionApprovedDate>
               <conditionDetail>DR B BLOGS NOMINATED SUPERVISOR</conditionDetail>
            </condition>
        </conditionDetails>
        <endorsementDetails>
          <endorsement>
               <endorsementType />
               <endorsementSubType />
               <endorsementCreateDate />
               <endorsementEndDate />
          </endorsement>
        </endorsementDetails>
        <undertakingDetails>
          <undertaking>
               <undertakingType>University Lectures</undertakingType>
               <undertakingApprovedDate>2014-12-18</undertakingApprovedDate>
               <undertakingText>The Doctor will undertake to deliver lectures to uni students.</undertakingText>
          </undertaking>
        </undertakingDetails>
          <notationDetails>
            <notationDetail>
               <notationCreateDate>1980-09-11</notationCreateDate> 
               <notationEndDate>2016-09-11</notationEndDate>
           <notation>Ineligible Orderly</notation>
            </notationDetail>
          </notationDetails>
        </registration>
    </registrationDetails>
    <employmentDetails>
      <positionTitle>Dr Dre</positionTitle>
      <sponsorOrganisationName>Aftermath Hospital</sponsorOrganisationName>
      <sponsorOrganisationContact>Eminem</sponsorOrganisationContact>
    </employmentDetails>
  </person>
  <person>
    <contactID>4400139361</contactID>
    <personalDetails>
      <givenName>Suzanne</givenName>
      <middleName>Lillian</middleName>
      <familyName>Jones</familyName>
      <title>MS</title>
      <gender>F</gender>
      <dateOfBirth>1971-12-13</dateOfBirth>      
      <dobAccuracy>AAA</dobAccuracy>
      <dateOfDeath>1905-09-22</dateOfDeath>
    </personalDetails>
    <residencyDetails>
      <residencyStatus>Australian Citizen</residencyStatus>
      <visaType />
      <passportNum />
      <countryOfIssue />
    </residencyDetails>
    <addressDetails>
      <address>
        <addressPurposeIndicator>Both preferred and practice</addressPurposeIndicator>
        <floorLevelNum />
      <floorLevelType />
      <lotNum />
        <postcode>4740</postcode>
        <state>QLD</state>
        <streetName>The Avenue</streetName>
        <streetNum>419</streetNum>
        <streetType>ST</streetType>
        <locality>ANDERGROVE</locality>
        <flatUnitNum />
      <flatUnitType />
        <sitePremisesName />
      </address>
    </addressDetails>
    <communications>
      <communication>
        <mediumCode>T</mediumCode>
      <areaCode>07</areaCode>
        <communicationDetails>49281771</communicationDetails>
      </communication>
      <communication>
        <mediumCode>E</mediumCode>
        <communicationDetails>suzanne.jones2@optus.com</communicationDetails>
      </communication>
    <communication>
        <mediumCode>M</mediumCode>
        <communicationDetails>0404009266</communicationDetails>
      </communication>
    </communications>
    <registrationDetails>
       <registration>
          <registrationID>NMW0000003085</registrationID>
          <profession>Nurse</profession>
          <division>Registered Nurse (Division 1)</division>
          <initialRegistrationStartDate>1994-03-15</initialRegistrationStartDate>
          <registrationType>General</registrationType>
          <registrationSubType />
          <registrationTypeStartDate>1994-03-15</registrationTypeStartDate>
          <registrationStatus>Registered</registrationStatus>
          <registrationStatusStartDate>2011-05-27</registrationStatusStartDate>
          <specialtyDetails>
            <specialtyDetail>
               <specialty>Being Excellent</specialty>
               <fieldOfSpecialtyPractice>Excellence</fieldOfSpecialtyPractice>
           <specialtyPracticeStartDate>2008-05-29</specialtyPracticeStartDate>
           <specialtyPracticeEndDate>2018-11-15</specialtyPracticeEndDate>
            </specialtyDetail>
          </specialtyDetails>
          <conditionDetails>
            <condition>
               <applicationRegistrationCondition>REJECTED</applicationRegistrationCondition>
               <conditionApprovedDate>1805-04-08</conditionApprovedDate>
               <conditionDetail>The lazy dog jumped up to bite the fox.</conditionDetail>
            </condition>
        </conditionDetails>
        <endorsementDetails>
          <endorsement>
               <endorsementType>Nurse Practitioner</endorsementType>
               <endorsementSubType>Nurse</endorsementSubType>
               <endorsementCreateDate>2011-04-30</endorsementCreateDate>
               <endorsementEndDate />
          </endorsement>
        </endorsementDetails>
        <undertakingDetails>
          <undertaking>
               <undertakingType>Education</undertakingType>
               <undertakingApprovedDate>2011-05-01</undertakingApprovedDate>
               <undertakingText>The Doctor will undertake training in new Pathology methods.</undertakingText>
          </undertaking>
        </undertakingDetails>
          <notationDetails>
            <notationDetail>
               <notationCreateDate />  
               <notationEndDate />  
           <notation />
            </notationDetail>
          </notationDetails>
        </registration>
    </registrationDetails>
    <employmentDetails>
      <positionTitle />
      <sponsorOrganisationName />
      <sponsorOrganisationContact />
    </employmentDetails>
  </person>
  <person>
    <contactID>6600027368</contactID>
    <personalDetails>
      <givenName>Mary</givenName>
      <middleName>Ann</middleName>
      <familyName>Smart</familyName>
      <title>MRS</title>
      <gender>F</gender>
      <dateOfBirth>1970-10-03</dateOfBirth>      
      <dobAccuracy>AAA</dobAccuracy>
      <dateOfDeath />
    </personalDetails>
    <residencyDetails>
      <residencyStatus>Kiwi</residencyStatus>
      <visaType>Temp</visaType>
      <passportNum>K7777777</passportNum>
      <countryOfIssue>New Zealand</countryOfIssue>
    </residencyDetails>
    <addressDetails>
      <address>
        <addressPurposeIndicator>Both preferred and practice</addressPurposeIndicator>
        <floorLevelNum />
      <floorLevelType />
      <lotNum />
        <postcode>4214</postcode>
        <state>QLD</state>
        <streetName>The Terrace</streetName>
        <streetNum>39</streetNum>
        <streetType>RD</streetType>
        <locality>ASHMORE</locality>
        <flatUnitNum />
      <flatUnitType />
        <sitePremisesName />
      </address>
    </addressDetails>
    <communications>
      <communication>
        <mediumCode>T</mediumCode>
      <areaCode>07</areaCode>
        <communicationDetails>48103280</communicationDetails>
      </communication>
      <communication>
        <mediumCode>E</mediumCode>
        <communicationDetails>maryann.smart@dodo.com</communicationDetails>
      </communication>
    <communication>
        <mediumCode>M</mediumCode>
        <communicationDetails>0414003242</communicationDetails>
      </communication>
    </communications>
    <registrationDetails>
       <registration>
          <registrationID>NMW0000114235</registrationID>
          <profession>Midwife</profession>
          <division />
          <initialRegistrationStartDate>1994-02-10</initialRegistrationStartDate>
          <registrationType>General</registrationType>
          <registrationSubType />
          <registrationTypeStartDate>1994-02-10</registrationTypeStartDate>
          <registrationStatus>Registered</registrationStatus>
          <registrationStatusStartDate>2011-05-21</registrationStatusStartDate>
          <specialtyDetails>
            <specialtyDetail>
               <specialty />
               <fieldOfSpecialtyPractice />
           <specialtyPracticeStartDate />
           <specialtyPracticeEndDate />
            </specialtyDetail>
          </specialtyDetails>
          <conditionDetails>
            <condition>
               <applicationRegistrationCondition />
               <conditionApprovedDate />
               <conditionDetail />
            </condition>
        </conditionDetails>
        <endorsementDetails>
          <endorsement>
               <endorsementType>Doctor</endorsementType>
               <endorsementSubType>Quack</endorsementSubType>
               <endorsementCreateDate>1999-01-01</endorsementCreateDate>
               <endorsementEndDate>2057-06-06</endorsementEndDate>
          </endorsement>
        </endorsementDetails>
        <undertakingDetails>
          <undertaking>
               <undertakingType>Community Work</undertakingType>
               <undertakingApprovedDate>2002-02-22</undertakingApprovedDate>
               <undertakingText>The Doctor will undertake community work.</undertakingText>
          </undertaking>
        </undertakingDetails>
          <notationDetails>
            <notationDetail>
               <notationCreateDate>2011-02-10</notationCreateDate> 
               <notationEndDate /> 
           <notation>Eligible midwife</notation>
            </notationDetail>
          </notationDetails>
        </registration>
    </registrationDetails>
    <employmentDetails>
      <positionTitle>Doctor Feelgood</positionTitle>
      <sponsorOrganisationName>Motley Crue Morgue</sponsorOrganisationName>
      <sponsorOrganisationContact>Nikki Sixx</sponsorOrganisationContact>
    </employmentDetails>
  </person>
</medicare>

Ответы [ 2 ]

2 голосов
/ 23 июня 2011

Попробуйте это (предполагается, что вы хотите, чтобы каждый mediumCode находился на отдельной строке):

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
  <xsl:output method="text" media-type="text" encoding="UTF-8" indent="no" />

  <xsl:param name="component"/>

  <xsl:variable name="q" select="'&quot;'" />
  <xsl:variable name="c" select="', '" />

  <xsl:template match="communication">
    <xsl:choose>
      <xsl:when test="$component=4">
        <xsl:value-of select="concat($q,../../contactID,$q)" />
        <xsl:apply-templates />
        <xsl:text>&#xA;</xsl:text>
      </xsl:when>
    </xsl:choose>
  </xsl:template>

  <xsl:template match="mediumCode | areaCode | communicationDetails">
    <xsl:value-of select="concat($c,$q,.,$q)" />
  </xsl:template>

  <xsl:template match="contactID" />
</xsl:stylesheet>

Я создал глобальные переменные для запятых и кавычек, чтобы было проще читать их при вызовах функций concat.

Эта таблица стилей обрабатывает любой элемент communication, выплевывая concatID его person предка, затем просто применяя шаблоны, которые обработают его три дочерних элемента.

Следующий шаблон обрабатывает три дочерних элемента одинаковым образом, выводя запятую с последующим значением в кавычках.

Последний шаблон запрещает вывод contactID самостоятельно. Процессоры XSLT по умолчанию будут искать шаблон для каждого узла в вашем дереве XML в последовательном порядке. Без этого шаблона он будет прибегать к поведению по умолчанию для текстового узла внутри него, то есть просто выводить его как есть.

Если вы хотите, чтобы все узлы связи были на одной линии, вы можете сделать это:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
  <xsl:output method="text" media-type="text" encoding="UTF-8" indent="no" />

  <xsl:param name="component"/>

  <xsl:variable name="q" select="'&quot;'" />
  <xsl:variable name="c" select="', '" />

  <xsl:template match="person">
    <xsl:choose>
      <xsl:when test="$component=4">
        <xsl:apply-templates />
        <xsl:text>&#10;</xsl:text>
      </xsl:when>
    </xsl:choose>
  </xsl:template>

  <xsl:template match="contactID">
    <xsl:value-of select="concat($q,.,$q)" />
  </xsl:template>

  <xsl:template match="mediumCode | areaCode | communicationDetails">
    <xsl:value-of select="concat($c,$q,.,$q)" />
  </xsl:template>
</xsl:stylesheet>

РЕДАКТИРОВАТЬ: Вот решение, которое производит постоянное количество полей в каждой строке в выходных данных:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
  <xsl:output method="text" media-type="text" encoding="UTF-8" indent="no" />

  <xsl:param name="component"/>

  <xsl:variable name="q" select="'&quot;'" />
  <xsl:variable name="c" select="', '" />

  <xsl:template match="communication[string-length(concat(mediumCode,areaCode,communicationDetails))!=0]">
    <xsl:choose>
      <xsl:when test="$component=4">
        <xsl:value-of select="concat(
            $q,../../contactID,$q,$c,
            $q,mediumCode,$q,$c,
            $q,areaCode,$q,$c,
            $q,communicationDetails,$q,'&#xA;'
          )" />
      </xsl:when>
    </xsl:choose>
  </xsl:template>

  <xsl:template match="contactID" />
</xsl:stylesheet>
1 голос
/ 23 июня 2011

Я немного изменил ваш код, чтобы избежать итерации. Вы можете получить другие данные, просто жестко запрограммировав индекс элемента communication. Я думаю, что это приемлемо в вашей ситуации. Более того, я не знаю, почему вы используете функцию normalize-space. Если во входном документе нет нескольких пробелов, этого можно избежать.

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:output method="text" media-type="text" encoding="UTF-8" indent="no" />
    <xsl:strip-space elements="*"/>

    <xsl:param name="component" select="4"/>
    <xsl:template match="medicare">
        <xsl:choose>
            <xsl:when test="$component=4">
                <xsl:apply-templates select="person"/>
            </xsl:when>
        </xsl:choose>
    </xsl:template>

    <xsl:template match="person">
      <xsl:value-of select="concat(
                '&quot;', contactID, '&quot;', ', ', '&quot;', 
                normalize-space(communications/
                communication[1]/mediumCode), '&quot;', ', ', '&quot;', 
                normalize-space(communications/
                communication[1]/areaCode), '&quot;', ', ', '&quot;',   
                normalize-space(communications/
                communication[1]/communicationDetails), '&quot;', ', ', '&quot;', 
                normalize-space(communications/
                communication[2]/mediumCode), '&quot;', ', ', '&quot;', 
                normalize-space(communications/
                communication[2]/communicationDetails), '&quot;', ', ', '&quot;', 
                normalize-space(communications/
                communication[3]/mediumCode), '&quot;', ', ', '&quot;', 
                normalize-space(communications/
                communication[3]/communicationDetails),'&quot;')" />
            <xsl:text>&#xa;</xsl:text>
    </xsl:template> 
</xsl:stylesheet>

Результат:

"0123456789", "T", "02", "62881111", "E", "john.smith@myisp.com.au", "M", "04140012225"
"5290001890", "T", "02", "92881781", "E", "rabina.smiley@ekit.com", "M", "04290012333"

Здесь следует более понятный подход, который дает тот же самый результат (применим, если ваш вариант использования действительно близок к данным, которые вы показываете в своем вопросе):

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:output method="text" media-type="text" encoding="UTF-8" indent="no" />
    <xsl:strip-space elements="*"/>

    <xsl:param name="component" select="4"/>

    <xsl:template match="medicare">
        <xsl:choose>
            <xsl:when test="$component=4">
                <xsl:apply-templates select="person"/>
            </xsl:when>
        </xsl:choose>
    </xsl:template>

    <xsl:template match="person">
        <xsl:value-of select="concat(
            '&quot;', contactID, '&quot;', ', ', '&quot;')"/>
        <xsl:apply-templates select="communications/communication/*"/>
        <xsl:text>&#xa;</xsl:text>
    </xsl:template>

    <xsl:template match="communication/*">  
        <xsl:value-of select="concat(., '&quot;')"/>
        <xsl:if test="count(../following-sibling::communication) + 
            count(following-sibling::*)!=0">
            <xsl:value-of select="concat( ', ', '&quot;')"/>
        </xsl:if>   
    </xsl:template> 

</xsl:stylesheet>
...