How to edit XML using XSL?

I am writing a dummy "MyAgenda" Java application that should support the maintenance of an XML file storing data.

Let's say I have an XML file, for example:

<myagenda>
  <contact>
    <name>Matthew Blake</name>
    <phone>12345678</phone>
  </contact>
</myagenda>

How to add a new one <contact>using XSLT?

Thanks.

+3
source share
3 answers

use xsl: param as a global parameter in the header of the xsl stylesheet.

<xsl:param name="newname"/>
<xsl:param name="newphone"/>

fill in the new parameters with your xslt engine, and then add a new element through the template:

(...)
<xsl:template match="myagenda">

<xsl:apply-templates select="contact"/>

<xsl:if test="string-length($newname)&gt;0">
 <xsl:element name="contact">
  <xsl:element name="name">
    <xsl:value-of select="$newname"/>
  </xsl:element>
  <xsl:element name="phone">
    <xsl:value-of select="$newphone"/>
  </xsl:element>
 </xsl:element>
</xsl:if>
</xsl:template>
(...)
+3
source

Start with a conversion that converts any XML document into itself.

- : node, . node - myagenda, -.

, , , , . :

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

: ", ?" , .

, . : XML document . , ; XSLT ( xsl:output):

<xsl:param name="contactName"/>
<xsl:param name="contactPhone"/>

, myagenda , , contact. , :

<xsl:template match="myagenda">
  <xsl:copy-of select=".">
     <xsl:apply-templates select="node() | @*"/>
     <contact>
        <name><xsl:value-of select="$contactName"/></name>
        <phone><xsl:value-of select="$contactPhone"/></phone>
     </contact>
  </xsl:copy-of>
</xsl:template>

XML , XSLT :

<xsl:variable name="contact" value="document('contact.xml')"/>
<xsl:variable name="contactName" value="$contact/*/name[1]'/>
<xsl:variable name="contactPhone" value=$contact/*/phone[1]'>

contact.xml name phone ( * , , ).

+4

XSLT converts 1 xml file to another XML file or text file.

+1
source

Source: https://habr.com/ru/post/1723534/


All Articles