【问题标题】:Removing node from NodeList of XML Doc从 XML Doc 的 NodeList 中删除节点
【发布时间】:2019-04-12 21:47:36
【问题描述】:

如果某些节点存在于以下数组中,我正在尝试从 XML 文档中删除它们:

 const removeNodesDataMap = [
    'Source',
    'ProductCode',
    'ProductCategory',
    'PublicationDateTime',
    'ArticleID',
    'Author'
 ];

我尝试使用 xmldom npm 包并使用 removeChild 方法如下:

function removeXmlNodes(str) {
    const xmlValue = new DomParser().parseFromString(str, 'text/xml');
    removeNodesDataMap.forEach(node => {
        const rNode = xmlValue.getElementsByTagName(node)[0];
        if (rNode) {
            const sNode = xmlValue.removeChild(rNode.parentNode);
        }
    });
    const serializer = XMLSerializer.serializeToString(xmlValue);
    return serializer;
}

但是,序列化程序仍然包含所有节点。根据它们是否与上述数组中的内容匹配来删除节点的最佳方法是什么?

XML 示例:

<Source>ABC</Source>
<ProductCode>77</ProductCode>
<ProductCategory>Performance</ProductCategory>
<PublicationDateTime>2019-03-06  17:04:5.000</PublicationDateTime>
<ArticleID>123254</ArticleID>
<Author/>
<records>
<record>some record stuff that I actually want to return along with node</record>
</records>

预期输出是:

"<records><record>some record stuff that I actually want to return along with node</record></records>"

有人可以帮忙吗?

【问题讨论】:

    标签: javascript node.js xml parsing


    【解决方案1】:

    当您的 xml 缺少根时,它似乎有点奇怪。我可以解决您的问题,但我需要将 xml 内容包装在根目录中。主要的变化是通过调用 node.ParentNode.remove(node) 来移除

    const { DOMParser, XMLSerializer } = require('xmldom');
    
    const removeNodesDataMap = [
      'Source',
      'ProductCode',
      'ProductCategory',
      'PublicationDateTime',
      'ArticleID',
      'Author',
    ];
    
    function removeXmlNodes(str) {
      const xmlValue = new DOMParser().parseFromString(`<root id="root">${str}</root>`, 'text/xml');
      removeNodesDataMap.forEach(node => {
        const rNode = xmlValue.getElementsByTagName(node)[0];
        if (rNode) {
          rNode.parentNode.removeChild(rNode);
        }
      });
      const serializer = new     XMLSerializer().serializeToString(xmlValue.getElementById('root'));
      return serializer;
    }
    
    const input = `
    <Source>ABC</Source>
    <ProductCode>77</ProductCode>
    <ProductCategory>Performance</ProductCategory>
    <PublicationDateTime>2019-03-06  17:04:5.000</PublicationDateTime>
    <ArticleID>123254</ArticleID>
    <Author/>
    <records>
    <record>some record stuff that I actually want to return along with node</record>
    </records>
    `;
    
    console.log(removeXmlNodes(input))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-06
      • 1970-01-01
      • 2014-09-13
      • 1970-01-01
      • 2019-04-12
      • 2016-11-05
      • 1970-01-01
      • 2020-01-15
      相关资源
      最近更新 更多