CodeSampleX

示例

saxes 6.0.0: parse XML elements with attributes using SaxesParser

已验证示例 — npm saxes 6.0.0: parse XML elements with attributes using SaxesParser. contract 在 node 22 · linux alpine/x64 · docker 上运行并通过.

sha256:7b9d154baf7ce23e49eb98b3969182f1fd81a83eaf702bfd0e567c53c7d1577a

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。 MIT-0

执行证据

声明的环境与签名的运行分开呈现,你可以看到这个样本究竟运行了什么、在哪里运行。

证据依据
签名契约通过
验证回执
1
构建过它的签名密钥
1
声明的环境 node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm

验证运行环境

环境 契约 阶段 运行日期
node 22 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1
2026-08-20

案例

HOW
目标
parse XML elements with attributes using SaxesParser
包
符号
  • SaxesParser
环境
node 22.23.2
创建时间
2026-08-20T22:47:02Z

契约

  1. assert SaxesParser parses XML elements and emits opentag, text, and closetag events
  2. assert SaxesParser captures element attributes accurately
  3. assert parseXml helper extracts structured element nodes and text content

文件

  • PROMPT.md
  • csx.json
  • index.js
  • package-lock.json
  • package.json
  • spec.json
  • test/contract.cjs

下载源代码构件 (tar.gz)

源代码

PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: parse XML elements with attributes using SaxesParser
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/saxes@6.0.0
Demonstrate these symbols/APIs:
  - SaxesParser
Constraints:
  - executionContext: node
Required runtime conditions:
  - ecosystem: npm
  - language: javascript
  - moduleSystem: cjs
  - runtime: node@22.23.2

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:2d41249d86c977f135c6b4ec2c50cca982e07dba2971c92d3b77de59fa548897","constraints":{"executionContext":"node"},"contract":["assert SaxesParser parses XML elements and emits opentag, text, and closetag events","assert SaxesParser captures element attributes accurately","assert parseXml helper extracts structured element nodes and text content"],"goal":"parse XML elements with attributes using SaxesParser","kind":"HOW","packages":["pkg:npm/saxes@6.0.0"],"schemaVersion":1,"symbols":["SaxesParser"]},"contractCommand":["node","test/contract.cjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","executionContext":"node","language":"javascript","libc":"glibc","libcVersion":"2.39","moduleSystem":"cjs","os":"linux","osVersionBucket":"24","packageManager":"npm","runtime":"node","runtimeVersion":"22.23.2","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/saxes@6.0.0"],"schemaVersion":1,"subject":"pkg:npm/saxes@6.0.0","symbols":["SaxesParser"],"verifierAdapter":"node-typescript@1"}
index.js
const { SaxesParser } = require("saxes");

/**
 * Parses an XML string into a structured list of tag and text events.
 * @param {string} xml - The XML string to parse.
 * @param {object} [options] - Parser options for SaxesParser.
 * @returns {Array<object>} - Array of parsed events.
 */
function parseXml(xml, options = {}) {
  const parser = new SaxesParser(options);
  const events = [];

  parser.on("opentag", (tag) => {
    events.push({
      type: "opentag",
      name: tag.name,
      attributes: Object.assign({}, tag.attributes),
      isSelfClosing: tag.isSelfClosing
    });
  });

  parser.on("text", (text) => {
    const trimmed = text.trim();
    if (trimmed.length > 0) {
      events.push({
        type: "text",
        text: trimmed
      });
    }
  });

  parser.on("closetag", (tag) => {
    events.push({
      type: "closetag",
      name: tag.name
    });
  });

  parser.write(xml).close();
  return events;
}

module.exports = {
  SaxesParser,
  parseXml
};
package-lock.json
{
  "name": "saxes-sample",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "saxes-sample",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "saxes": "6.0.0"
      }
    },
    "node_modules/saxes": {
      "version": "6.0.0",
      "resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz",
      "integrity": "sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==",
      "license": "ISC",
      "dependencies": {
        "xmlchars": "^2.2.0"
      },
      "engines": {
        "node": ">=v12.22.7"
      }
    },
    "node_modules/xmlchars": {
      "version": "2.2.0",
      "resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz",
      "integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==",
      "license": "MIT"
    }
  }
}
package.json
{
  "name": "saxes-sample",
  "version": "1.0.0",
  "description": "parse XML elements with attributes using SaxesParser",
  "main": "index.js",
  "scripts": {
    "test": "node test/contract.cjs"
  },
  "dependencies": {
    "saxes": "6.0.0"
  },
  "license": "MIT-0"
}
spec.json
{
  "schemaVersion": 1,
  "goal": "parse XML elements with attributes using SaxesParser",
  "kind": "HOW",
  "packages": [
    "pkg:npm/saxes@6.0.0"
  ],
  "symbols": [
    "SaxesParser"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "runtime": "node@22.23.2"
  }
}
test/contract.cjs
const assert = require("node:assert");
const { SaxesParser, parseXml } = require("../index.js");

// Test 1: Direct SaxesParser usage parses XML elements and captures attributes
{
  const parser = new SaxesParser();
  const opened = [];
  const closed = [];
  const textChunks = [];

  parser.on("opentag", (tag) => {
    opened.push(tag);
  });

  parser.on("text", (text) => {
    textChunks.push(text);
  });

  parser.on("closetag", (tag) => {
    closed.push(tag);
  });

  parser.write('<book id="b1" category="fiction"><title>The Sample</title><author>Author</author></book>');
  parser.close();

  assert.strictEqual(opened.length, 3);
  assert.strictEqual(opened[0].name, "book");
  assert.strictEqual(opened[0].attributes.id, "b1");
  assert.strictEqual(opened[0].attributes.category, "fiction");
  assert.strictEqual(opened[1].name, "title");
  assert.strictEqual(opened[2].name, "author");

  assert.strictEqual(closed.length, 3);
  assert.strictEqual(closed[0].name, "title");
  assert.strictEqual(closed[1].name, "author");
  assert.strictEqual(closed[2].name, "book");

  assert.strictEqual(textChunks.join(""), "The SampleAuthor");
}

// Test 2: parseXml helper parses nested XML elements and attributes
{
  const xml = '<root status="active"><item key="1">First</item><item key="2" flag="true">Second</item></root>';
  const results = parseXml(xml);

  assert.strictEqual(results.length, 8);
  assert.deepStrictEqual(results[0], {
    type: "opentag",
    name: "root",
    attributes: { status: "active" },
    isSelfClosing: false
  });
  assert.deepStrictEqual(results[1], {
    type: "opentag",
    name: "item",
    attributes: { key: "1" },
    isSelfClosing: false
  });
  assert.deepStrictEqual(results[2], {
    type: "text",
    text: "First"
  });
  assert.deepStrictEqual(results[3], {
    type: "closetag",
    name: "item"
  });
  assert.deepStrictEqual(results[4], {
    type: "opentag",
    name: "item",
    attributes: { key: "2", flag: "true" },
    isSelfClosing: false
  });
  assert.deepStrictEqual(results[5], {
    type: "text",
    text: "Second"
  });
  assert.deepStrictEqual(results[6], {
    type: "closetag",
    name: "item"
  });
  assert.deepStrictEqual(results[7], {
    type: "closetag",
    name: "root"
  });
}

// Test 3: SaxesParser handles self-closing tags
{
  const xml = '<items><item id="self1"/><item id="self2"/></items>';
  const results = parseXml(xml);

  assert.strictEqual(results.length, 6);
  assert.strictEqual(results[1].name, "item");
  assert.strictEqual(results[1].isSelfClosing, true);
  assert.deepStrictEqual(results[1].attributes, { id: "self1" });
  assert.strictEqual(results[3].name, "item");
  assert.strictEqual(results[3].isSelfClosing, true);
  assert.deepStrictEqual(results[3].attributes, { id: "self2" });
}

console.log("All SaxesParser contract assertions passed successfully.");

原始种子者

匿名