【问题标题】:Save XML parsed by JSDOM as a file将 JSDOM 解析的 XML 保存为文件
【发布时间】:2020-04-27 08:29:20
【问题描述】:

我可以像这样解析 XML:

import JSDOM from "jsdom";
const myXml = "... some xml loaded from somewhere ...";
const dom = new JSDOM.JSDOM(myXml);

当我用谷歌搜索 “jsdom save xml” 时,我真的很惊讶,但我什么也没得到。我认为 JSDOm 是最流行的 XML 操作库之一。

在一个答案中,我看到了这个:

window.document.documentElement.outerHTML

由于某种原因会产生垃圾代码,例如它会转换:

<Node>
   <Child attr="attr"/>
   <Child attr="attr"/>
   <Child attr="attr"/>
   <Child attr="attr"/>
</Node>

<Node>
   <Child attr="attr">
   <Child attr="attr">
   <Child attr="attr">
   <Child attr="attr">
   </Child></Child></Child></Child>
</Node>

它还以以下方式开始文档:

<html><head></head><body><globe xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">

请注意,Globe 是源 XML 的根元素。它还以小写形式生成所有内容。

【问题讨论】:

  • 你可能需要告诉 JSDOM 它没有解析 HTML。
  • 是的,看起来它将文档解释为 HTML。这不是立即显而易见的,因为选择器等工作。

标签: javascript node.js xml jsdom


【解决方案1】:

保存文档的方法是正确的。但是解析的方法是错误的。 JSDOM 需要 HTML 并创建浏览器 DOM 的实例。并且必须这样使用,所以步骤和在浏览器中解析XML的时候一样:

// Create empty DOM, the imput param here is for HTML not XML, and we don want to parse HTML
const dom = new JSDOM.JSDOM("");
// Get DOMParser, same API as in browser
const DOMParser = dom.window.DOMParser;
const parser = new DOMParser;
// Create document by parsing XML
const document = parser.parseFromString(xml, "text/xml");

// save the xml after modifications 
const xmlString = document.documentElement.outerHTML;

【讨论】:

    猜你喜欢
    • 2013-11-11
    • 2015-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多