Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01AmyPfuNc4sCRfaF3oURXZz
113 lines
5.1 KiB
TypeScript
113 lines
5.1 KiB
TypeScript
// Kleiner XML-Leser ohne Abhängigkeiten, für GAEB DA XML. Kennt Elemente, Attribute, Text, CDATA und die
|
||
// üblichen Entitäten; Kommentare, Verarbeitungsanweisungen und DOCTYPE werden übersprungen.
|
||
// Namensräume fallen weg: aus <g:Item> wird „Item“.
|
||
|
||
export interface XmlElement {
|
||
name: string;
|
||
attr: Record<string, string>;
|
||
kinder: XmlKnoten[];
|
||
}
|
||
export type XmlKnoten = XmlElement | string;
|
||
|
||
const ENTITAETEN: Record<string, string> = { lt: "<", gt: ">", amp: "&", quot: '"', apos: "'", nbsp: " " };
|
||
|
||
export function entschluesseln(t: string): string {
|
||
return t.replace(/&(#x[0-9a-fA-F]+|#\d+|[a-zA-Z]+);/g, (ganz, e: string) => {
|
||
if (e[0] === "#") {
|
||
const n = e[1] === "x" || e[1] === "X" ? parseInt(e.slice(2), 16) : parseInt(e.slice(1), 10);
|
||
return Number.isFinite(n) ? String.fromCodePoint(n) : ganz;
|
||
}
|
||
return ENTITAETEN[e] ?? ganz;
|
||
});
|
||
}
|
||
|
||
const ohnePraefix = (n: string) => n.slice(n.indexOf(":") + 1);
|
||
|
||
/** Liest ein XML-Dokument und gibt das Wurzelelement zurück */
|
||
export function leseXml(text: string): XmlElement {
|
||
const wurzel: XmlElement = { name: "#dokument", attr: {}, kinder: [] };
|
||
const stapel: XmlElement[] = [wurzel];
|
||
let i = 0;
|
||
const n = text.length;
|
||
while (i < n) {
|
||
const lt = text.indexOf("<", i);
|
||
if (lt < 0) { stapel[stapel.length - 1]!.kinder.push(entschluesseln(text.slice(i))); break; }
|
||
if (lt > i) stapel[stapel.length - 1]!.kinder.push(entschluesseln(text.slice(i, lt)));
|
||
if (text.startsWith("<!--", lt)) { const e = text.indexOf("-->", lt + 4); i = e < 0 ? n : e + 3; continue; }
|
||
if (text.startsWith("<![CDATA[", lt)) {
|
||
const e = text.indexOf("]]>", lt + 9);
|
||
stapel[stapel.length - 1]!.kinder.push(text.slice(lt + 9, e < 0 ? n : e));
|
||
i = e < 0 ? n : e + 3;
|
||
continue;
|
||
}
|
||
if (text.startsWith("<?", lt)) { const e = text.indexOf("?>", lt + 2); i = e < 0 ? n : e + 2; continue; }
|
||
if (text.startsWith("<!", lt)) {
|
||
// DOCTYPE, ggf. mit [ … ]
|
||
let tiefe = 0, j = lt + 2;
|
||
for (; j < n; j++) { const c = text[j]; if (c === "[") tiefe++; else if (c === "]") tiefe--; else if (c === ">" && tiefe <= 0) break; }
|
||
i = j + 1;
|
||
continue;
|
||
}
|
||
// Ende des Tags finden, Anführungszeichen beachten
|
||
let j = lt + 1, quote = "";
|
||
for (; j < n; j++) {
|
||
const c = text[j]!;
|
||
if (quote) { if (c === quote) quote = ""; } else if (c === '"' || c === "'") quote = c; else if (c === ">") break;
|
||
}
|
||
if (j >= n) throw new Error("Die XML-Datei ist unvollständig (ein Tag endet nicht).");
|
||
const tag = text.slice(lt + 1, j);
|
||
i = j + 1;
|
||
if (tag.startsWith("/")) {
|
||
const name = ohnePraefix(tag.slice(1).trim());
|
||
// bis zum passenden offenen Element schließen (verzeiht fehlerhafte Verschachtelung)
|
||
for (let k = stapel.length - 1; k > 0; k--) if (stapel[k]!.name === name) { stapel.length = k; break; }
|
||
continue;
|
||
}
|
||
const leer = tag.endsWith("/");
|
||
const inhalt = leer ? tag.slice(0, -1) : tag;
|
||
const m = /^\s*([^\s/>]+)/.exec(inhalt);
|
||
if (!m) continue;
|
||
const el: XmlElement = { name: ohnePraefix(m[1]!), attr: {}, kinder: [] };
|
||
const re = /([^\s=]+)\s*=\s*("([^"]*)"|'([^']*)')/g;
|
||
let a: RegExpExecArray | null;
|
||
const rest = inhalt.slice(m[0].length);
|
||
while ((a = re.exec(rest))) el.attr[ohnePraefix(a[1]!)] = entschluesseln(a[3] ?? a[4] ?? "");
|
||
stapel[stapel.length - 1]!.kinder.push(el);
|
||
if (!leer) stapel.push(el);
|
||
}
|
||
const erstes = wurzel.kinder.find((k): k is XmlElement => typeof k !== "string");
|
||
if (!erstes) throw new Error("Die Datei enthält kein XML.");
|
||
return erstes;
|
||
}
|
||
|
||
export const elemente = (e: XmlElement, name?: string): XmlElement[] =>
|
||
e.kinder.filter((k): k is XmlElement => typeof k !== "string" && (!name || k.name === name));
|
||
export const kind = (e: XmlElement | undefined, name: string): XmlElement | undefined => (e ? elemente(e, name)[0] : undefined);
|
||
/** Pfad aus Kindnamen, z. B. pfad(item, "Description", "CompleteText") */
|
||
export const pfad = (e: XmlElement | undefined, ...namen: string[]): XmlElement | undefined => namen.reduce<XmlElement | undefined>((x, n) => kind(x, n), e);
|
||
|
||
/** reiner Text eines Elements, Leerraum zusammengefasst */
|
||
export function textVon(e: XmlElement | undefined): string {
|
||
if (!e) return "";
|
||
const teile: string[] = [];
|
||
const lauf = (x: XmlKnoten) => { if (typeof x === "string") teile.push(x); else x.kinder.forEach(lauf); };
|
||
lauf(e);
|
||
return teile.join("").replace(/\s+/g, " ").trim();
|
||
}
|
||
|
||
/** Fließtext aus <p>, <br>, <span> (GAEB-Texte): Absätze als Zeilenumbruch */
|
||
export function absatzText(e: XmlElement | undefined): string {
|
||
if (!e) return "";
|
||
let aus = "";
|
||
const lauf = (x: XmlKnoten) => {
|
||
if (typeof x === "string") { aus += x.replace(/\s+/g, " "); return; }
|
||
if (x.name === "br") { aus += "\n"; return; }
|
||
const block = x.name === "p" || x.name === "div" || x.name === "li";
|
||
if (block && aus && !aus.endsWith("\n")) aus += "\n";
|
||
x.kinder.forEach(lauf);
|
||
if (block && !aus.endsWith("\n")) aus += "\n";
|
||
};
|
||
lauf(e);
|
||
return aus.split("\n").map((z) => z.trim()).join("\n").replace(/\n{3,}/g, "\n\n").trim();
|
||
}
|