Search code examples
javascriptxmle4xmirth

Use Javascript E4X to selectively rename XML tags


I am using javascript to manipulate XML in a non-browser context (no DOM), and am looking for an E4X expression to rename a list of tags. For any given tag, I don't necessarily know ahead of time what it is called, and I only want to rename it if it contains a given substring.

As I very contrived example, I may have:

someXML = <Favourites>
              <JillFaveColour>Blue</JillFaveColour>
              <JillFaveCandy>Smarties</JillFaveCandy>
              <JillFaveFlower>Rose</JillFaveFlower>
          <Favourites>

and I want to turn the XML into:

<Favourites>
    <GaryFaveColour>Blue</GaryFaveColour>
    <GaryFaveCandy>Smarties</GaryFaveCandy>
    <GaryFaveFlower>Rose</GaryFaveFlower>
<Favourites>

However, there may be more tags or fewer tags, and I won't know ahead of time what their full name is. I only rename them if they contain a given substring (in my example, the substring is "Jill").


Solution

  • For renaming elements, use setLocalName(newName). For your "I don't know all the tag names in advance" problem, just iterate over the elements and call their localName() methods (if node.length() === 1 && node.nodeKind() === "element") to get their tag names.