regular expression to replace an xml attribute

前端 未结 3 431
小蘑菇
小蘑菇 2021-01-14 13:17

I have an xml file of the form:

stuff

There are many propertie

相关标签:
3条回答
  • 2021-01-14 13:25

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

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

    0 讨论(0)
  • 2021-01-14 13:25

    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.

    0 讨论(0)
  • 2021-01-14 13:26

    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.

    0 讨论(0)
提交回复
热议问题