Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xpath for Find & Replace?

Tags:

replace

xml

xpath

Fellow Forum Members, I'm new to Xpath and have the following question. Let's say for example I have 300 separate XML files and I need to make a global text change that may impact only 40 of the XML files. Is it possible using Xpath to perform a find & replace operation among all 300 XML files? Let's say for example the words I need to globally change are these words, "LBRT Assembly" change to "LBRS assembly". Does Xpath offer the ability to perform such an operation? I know Xpath is good at querying XML elements. However, can it also perform a find and replace operation? What is the best application available one can use that will assist one in coding complex Xpath query commands? Any opinion will be greatly welcomed. Thanks in advance.

like image 512
Matrix Avatar asked Oct 28 '25 09:10

Matrix


1 Answers

XPath cannot modify an XML file. For that you need XSLT or XQuery.

If this really is a global change (that is, if you want to change this text regardless of the context where it appears) then I would be very inclined myself to do it using a text editor: that goes against the advice I invariably give which says when processing XML data you should use XML tools. But if finding the text to change does depend on the XML context, I would write a little XSLT 2.0 program to do it: it's probably about a dozen lines. The core would be:

(a) a standard identity template to copy elements unchanged

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

(b) something to drive the processing:

<xsl:template name="main">
  <xsl:apply-templates select="collection('my/dir/?select=*.xml')"/>
</xsl:template>

(e) a template to create a new output document for each input document

<xsl:template match="/">
  <xsl:result-document href="{replace(document-uri(.), '/dir/', '/outdir/')}">
    <xsl:apply-templates/>
  </xsl:result-document>
</xsl:template> 

(d) a template to modify the text nodes

<xsl:template match="text()">
  <xsl:value-of select="replace(., 'xxx', 'yyy')"/>
</xsl:template>
like image 57
Michael Kay Avatar answered Oct 31 '25 04:10

Michael Kay



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!