2015-08-28 3 views
1

У меня есть это требование: мне нужно получить значение элемента из XML и условно заполнить его пустым элементом. Единственное, что приходит на ум, это использовать XSLT.Замена тега элемента значением для конца тега

Состояние: Если PaymentMethodCode равно NONE, или не существует, мне нужно, чтобы заполнить этот пустой элемент: <eb:NoPayment/>

Например:

входного файла:

<Invoice xmlns="http://schema.infor.com/InforOAGIS/2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://schema.infor.com/InforOAGIS/2 http://schema.infor.com/2.12.x/InforOAGIS/BODs/SyncInvoice.xsd" Language="ger" DocumentTitle="Invoice"> 
    <Country CountryCode="AT">Austria</Country> 
    <PaymentMethodCode>NONE</PaymentMethodCode> 
</Invoice> 

Мой ожидаемый выход должен быть:

<eb:Invoice xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.ebinterface.at/schema/4p1/ http://www.ebinterface.at/schema/4p1/" xmlns:eb="http://www.ebinterface.at/schema/4p1/" eb:Language="ger" eb:DocumentTitle="Invoice">> 
    <eb:Country eb:CountryCode="AT">Austria</eb:Country> 
    <eb:PaymentMethod> 
      <eb:NoPayment/> 
    </eb:PaymentMethod> 
</eb:Invoice> 

Возможно ли это? Я не знаю, как это сделать в XSLT.

+0

'' даже не XML, пустой элемент будет выглядеть как '' или ''. Также в вашем образце отсутствует какое-либо объявление пространства имен, связывающее префикс 'eb' с URI пространства имен. –

+0

спасибо за уведомление, я только что редактировал свой XML, а также пустой тег. –

+0

Каков ожидаемый результат, когда условие не выполняется? –

ответ

1

XSLT 1.0 решение:

<?xml version="1.0" encoding="UTF-8"?> 
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
    xmlns:infor="http://schema.infor.com/InforOAGIS/2" 
    xmlns:eb="http://www.ebinterface.at/schema/4p1/" 
    exclude-result-prefixes="infor" 
    version="1.0"> 

    <xsl:template match="@* | node()"> 
     <xsl:copy> 
      <xsl:apply-templates select="@* | node()"/> 
     </xsl:copy> 
    </xsl:template> 

    <xsl:template match="infor:Invoice" priority="1"> 
     <eb:Invoice> 
      <!--handle any existing child content--> 
      <xsl:apply-templates select="@* | node()"/> 

      <xsl:if test="not(infor:PaymentMethodCode)"> 
       <!--create eb:PaymentMethodCode/eb:NoPayment--> 
       <xsl:call-template name="PaymentMethodCode"/> 
      </xsl:if> 
     </eb:Invoice> 
    </xsl:template> 

    <!--If there is not text node, or if the value is 'NONE', 
     create an empty NoPayment element--> 
    <xsl:template match="infor:PaymentMethodCode[not(text()) or .='NONE']" 
        name="PaymentMethodCode" priority="1"> 
     <eb:PaymentMethodCode> 
      <eb:NoPayment/> 
     </eb:PaymentMethodCode> 
    </xsl:template> 

    <!--Change the namespace for InforOAGIS elements --> 
    <xsl:template match="*[namespace-uri()='http://schema.infor.com/InforOAGIS/2']"> 
     <xsl:element name="eb:{local-name()}"> 
      <xsl:apply-templates select="@*|node()"/> 
     </xsl:element> 
    </xsl:template> 

    <!--Change the namespace of attributes from InforOAGIS elements --> 
    <xsl:template match="*[namespace-uri()='http://schema.infor.com/InforOAGIS/2']/@*"> 
     <xsl:attribute name="eb:{local-name()}"> 
      <xsl:value-of select="."/> 
     </xsl:attribute> 
    </xsl:template> 

</xsl:stylesheet> 
+0

Для других элементов, которые изменяются с 'infor: *' на 'eb: *'? Затем нужно настроить последний шаблон. Вместо '', который не включает атрибуты, это должно быть ''. Я уточню свой ответ. –

+0

привет @ Мады, спасибо за отзыв. Этот код очень полезен, и в настоящее время я его использую. Однако атрибуты не заполнялись. Я только что редактировал свой образец INPUT FILE. Я добавил Language = "ger", DocumentTitle = "Invoice" и элемент Country с атрибутом CountryCode. –

1

Я просто сделал следующий XSLT:

<?xml version="1.0" encoding="UTF-8"?> 
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
    xmlns:infor="http://schema.infor.com/InforOAGIS/2" xmlns:xs="http://www.w3.org/2001/XMLSchema" 
    exclude-result-prefixes="xs" version="2.0"> 

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

    <xsl:template match="infor:Invoice"> 
     <xsl:copy> 
      <xsl:choose> 
       <xsl:when test="not(exists(infor:PaymentMethodCode))"> 
        <xsl:element name="PaymentMethodCode" namespace="http://schema.infor.com/InforOAGIS/2"> 
         <xsl:element name="NoPayment" namespace="http://schema.infor.com/InforOAGIS/2"/> 
        </xsl:element> 
       </xsl:when>     
      </xsl:choose> 
      <xsl:apply-templates select="*|text()|@*"/> 
     </xsl:copy> 
    </xsl:template> 

    <xsl:template match="infor:PaymentMethodCode"> 
     <xsl:copy> 
      <xsl:choose> 
       <xsl:when test="text()='NONE'"> 
        <xsl:element name="NoPayment" namespace="http://schema.infor.com/InforOAGIS/2"/> 
       </xsl:when> 
       <xsl:when test="not(text())"> 
        <xsl:element name="NoPayment" namespace="http://schema.infor.com/InforOAGIS/2"/> 
       </xsl:when> 
       <xsl:otherwise> 
        <xsl:apply-templates select="*|text()|@*"/> 
       </xsl:otherwise> 
      </xsl:choose> 
     </xsl:copy> 
    </xsl:template> 

    <xsl:template match="*|text()|@*"> 
     <xsl:copy> 
      <xsl:apply-templates select="*|text()|@*"/> 
     </xsl:copy> 
    </xsl:template> 
</xsl:stylesheet> 

Это создаст элемент NoPayment, если нет PaymentMethodCode дано или содержит значение «NONE».

Вход:

<Invoice xmlns="http://schema.infor.com/InforOAGIS/2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://schema.infor.com/InforOAGIS/2 http://schema.infor.com/2.12.x/InforOAGIS/BODs/SyncInvoice.xsd"> 
    <PaymentMethodCode></PaymentMethodCode> 
    <PaymentMethodCode>NONE</PaymentMethodCode> 
    <PaymentMethodCode>something elese</PaymentMethodCode> 
</Invoice> 

дает выход:

<?xml version="1.0" encoding="UTF-8"?> 
<Invoice xmlns="http://schema.infor.com/InforOAGIS/2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://schema.infor.com/InforOAGIS/2 http://schema.infor.com/2.12.x/InforOAGIS/BODs/SyncInvoice.xsd"> 
    <PaymentMethodCode><NoPayment/></PaymentMethodCode> 
    <PaymentMethodCode><NoPayment/></PaymentMethodCode> 
    <PaymentMethodCode>something elese</PaymentMethodCode> 
</Invoice> 
+0

привет @FiveO, спасибо за отзыв. –

Смежные вопросы