Search code examples
lua

xml tag with attribute name changing using lua


I am new in lua and i would like to change XML tag and attribute name. My XML is:

<art>
    <fm>
    <art-meta>
            <his>
            <date date-type="rec"><day>23</day><month>1</month><year>2002</year></date>
            <date date-type="acc"><day>21</day><month>4</month><year>2002</year></date>
            </his>
    </art-meta>
    </fm>
</art>

I had tried FileGlobal = string.gsub(FileGlobal,"<date data-type=\"rec\">", "<date-rec>") and doesn't work?

I would like to change <date date-type="rec"> to <date-rec>. How to achieve this?


Solution

  • There is a typo in the pattern (the second parameter of gsub) which looks for date data-type instead of what we see in the xml, date date-type.
    Beyond that, there is an actual issue in the pattern to be aware of: Lua patterns use special characters, like - $ ^ () [ %. You must escape the - in date-type like this: date%-type.
    To a lesser extent, it is also worth noting that you don't need to escape the double quotation marks (although this would work). You can wrap your strings in single quotes or double brackets and the double quotes inside will be recognized as part of the string.
    Example: 'Foo "egg" bar' or [[Foo "egg" bar]]
    Final example of a working pattern: Typo fixed, dash escaped. '<date date%-type="rec">'