I have an xml file of the form:
stuff
There are many propertie
/property name=\"foo\" value=\"([^\"]*)\"/
Then just replace the first submatch with the new value of your wishing.
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.
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.