-1

I am building an app that lets users interact with xml files that they have uploaded. I need to make the xml file interactive for the user.

const testXML: string = `
  <testenv:header>
    <title>Page Title</title>
  </testenv:header>
  <testenv:body>
    <NumOne>one</NumOne>
    <NumTen>10</NumTen>
    <Finally>finally</Finally>
  </testenv:body>`

I want to make turn the opening element tags and innerXML into links. Im not sure if regex is the best way to do this or if there are other options. The result would look like the following:

<testenv:header>
  <title>Page Title</title>
</testenv:header>
<testenv:body>
  <testtag />
  <NumOne>one</NumOne>
  <NumTen>10</NumTen>
  <Finally>finally</Finally>
</testenv:body>

Of note here is that I am only turning the opening element tags and innerXML into links. I do not want to make the closing xml tags links unless it is an element with only one tag like <testtag />.

arctic
  • 609
  • 3
  • 11
  • 19

2 Answers2

1

Well xslt is a great language.

As a start you could you this:

<?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" version="1.0" encoding="UTF-8" indent="yes"/>
  <xsl:strip-space elements="*"/>
  
  <xsl:template match="*">
    &lt;<a href="#"><xsl:value-of select="name()"/></a>&gt;
    <xsl:apply-templates/>
    &lt;<xsl:value-of select="name()"/>&gt;
  </xsl:template>

  <xsl:template match="*[not(node())]">
    &lt;<a href="#"><xsl:value-of select="name()"/></a>/&gt;
  </xsl:template>
  
  <xsl:template match="*[not(*)]/text()">
    <a href="#"><xsl:value-of select="."/></a>
  </xsl:template>
    
</xsl:stylesheet>

You then would have to think about how to give that the correct visual structure.

Siebe Jongebloed
  • 3,906
  • 2
  • 14
  • 19
0

And, if you want to modify an XML structure, in my opinion there's only one way to do it:

  • Use an XML parser to turn the XML into a data structure.

  • Modify the data structure.

  • Use the same tool to turn the modified data structure back into XML.

In other words, don't try to treat the XML "as a string" and to write code to modify it (or, search it) in that fashion. (If you need to search it, follow Siebe's advice above and use the XSLT pseudo-language.) Treat the XML as a "black box," and use standard XML tools to manipulate it. (libxml is an industry standard.)

Mike Robinson
  • 8,490
  • 5
  • 28
  • 41