2

I would like to remove spaces and quotes from the value of XML tag <ns:tag2> in my XML file on Linux(spaces to be removed only for this tag not other places).

Sample XML content looks like below.

<ns:tag1>
    <ns:tag2>Abcdef qwert/denn+hkg kmknn xyz""""""""""</ns:tag2> 
</ns:tag1>

But I need the file to be written as shown below.

<ns:tag1>
    <ns:tag2>Abcdefqwert/denn+hkgkmknnxyz</ns:tag2> 
</ns:tag1>

I have seen the solution at Remove string with spaces and quotes from xml file and tried using sed command to remove the quotes but no luck.

sed  's/ ""//g'  temp.xml

Please suggest me right syntax for the same. It is fine if we can do this in 2 different steps.

3
  • 1
    Why would you try to remove quotes? You only want to remove spaces, and keep the quotes according to your question. Do you also need to remove quotes? And where should spaces be removed from? Everywhere in the file? Only in the <ns:tag2> tags? In all tags? Where else can you have spaces?
    – terdon
    Jun 3 '20 at 18:30
  • Apologies @terdon . Corrected my copy paste mistake by removing the quotes Jun 3 '20 at 19:12
  • @terdo - Spaces should be removed only in <ns:tag2>. The file could have spaces in other tags. Example : <?xml version="1.0" encoding="UTF-8" ?> Jun 3 '20 at 22:49
2

Here's an XSLT 3.0 transformation that does the job.

<xsl:transform version="3.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:mode on-no-match="shallow-copy"/>
  <xsl:template match="ns:tag2/text()" xmlns:ns="xxxxx">
      <xsl:value-of select="translate(., '&quot; ', '')"/>        
  </xsl:template>
</xsl:template>

Replace xxxxx with the actual namespace URI (not shown in your example).

Don't try to process XML at the lexical level using non-XML-aware tools like sed. We see hundreds of problems on StackOverflow from people having to cope with bad XML, invariably produced by such methods.

2

You can use an XML parser to parse your XML. I like xmlstarlet myself.

I've modified your sample to provide a (vaguely) plausible namespace declaration for ns:

<ns:root xmlns:ns="localns">
  <ns:tag1>
    <ns:tag2>Abcdef qwert/denn+hkg kmknn xyz""""""""""</ns:tag2>
  </ns:tag1>
</ns:root>

At this point you can replace the spaces and quotes with nothing:

xmlstarlet edit -N ns=localns -u '//ns:tag2/text()' -x "translate(., ' \"', '')" xmlfile

Result

<?xml version="1.0"?>
<ns:root xmlns:ns="localns">
  <ns:tag1>
    <ns:tag2>Abcdefqwert/denn+hkgkmknnxyz</ns:tag2>
  </ns:tag1>
</ns:root>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.