Daniel
Daniel

Reputation: 24775

regular expression to replace an xml attribute

I have an xml file of the form:

<property name="foo" value="this is a long value">stuff</property>

There are many properties but I want to match the one with name foo and then replace its value attribute with something else as so:

<property name="foo" value="yet another long value">stuff</property>

I was thinking to write a regular expression to match everything after "foo" to the end of the tag ( ">" ) and replace that, but I can't seem to get the syntax right.

I'm trying to do this using sed, if that's any help.

Upvotes: 4

Views: 13735

Answers (3)

fzembow
fzembow

Reputation: 343

If you're doing this in the context of a browser, you could create a throwaway DOM node containing the XML and just walk that to replace attribute values.

This function will call a callback on every child node:

const walkDOM = (node, callback) => {
  callback(node);
  [...node.children].forEach(child => {
    walkDOM(child, callback)
  });
}

You can then use this to update any attributes matching conditions you'd like (here replacing any, assuming you have an XML string called svgXml:

  const containerEl = document.createElement('div');
  containerEl.innerHTML = svgXml;

  walkDOM(containerEl, el => {
    const attributes = [...el.attributes];
    attributes.forEach(attr => {
      if (attr.name === 'foo' && attr.value === 'this is a long value']) {
        attr.value = 'yet another long value';
      }
    });
  });

  const outputSvgXml = containerEl.innerHTML;

Of course you could further optimize this by using querySelectorAll(property) to only walk <property> nodes, etc.

I found this useful for updating an SVG while taking advantage of the browser's robustness.

Upvotes: 0

Tommi Forsstr&#246;m
Tommi Forsstr&#246;m

Reputation: 1467

/property name=\"foo\" value=\"([^\"]*)\"/

Then just replace the first submatch with the new value of your wishing.

Upvotes: 7

SingleNegationElimination
SingleNegationElimination

Reputation: 156188

You probably don't want to use a regex for manipulating an xml file. Please instead consider xslt, which is aware of xml rules and won't cause your transformed document to become malformed.

Upvotes: 5

Related Questions