Home > database >  How to get XML Attributes with XPath in JSDOM
How to get XML Attributes with XPath in JSDOM

Time:11-23

I can't seem to be able to get XML Attributes using JSDOM and XPath Syntax on this XML Snippet.

<PARAGRAPH>
    This is a text, about something, that happened on 
    <DATE ISO="20131117">17.November 2013</DATE>
    . It is a very important date.
</PARAGRAPH>

By my understanding PARAGRAPH/DATE/@ISO is valid XPath Syntax for the Attribute and it's working just fine on sites like Xpather

Minimal working example:

import { JSDOM } from "jsdom";

const xml = `
<PARAGRAPH>
    This is a text, about something, that happened on 
    <DATE ISO="20131117">17.November 2013</DATE>
    . It is a very important date.
</PARAGRAPH>
`;

const dom = new JSDOM(xml, {contentType: "application/xml"});
const doc = dom.window.document;

// 2: XPathResult.STRING_TYPE
const date = doc.evaluate("PARAGRAPH/DATE/@ISO", doc, null, 2, null).stringValue;

console.log(date);

Expected Result: "20131117"

Actual Result: ""

Other non-working approaches

PARAGRAPH//DATE/@ISO, string(PARAGRAPH/DATE/@ISO), XPath.FIRST_ORDERED_NODE_TYPE

The evaluation seems to come back empty.

CodePudding user response:

Perhaps try

const dateEl = doc.evaluate("PARAGRAPH/DATE", doc, null, 9, null).singleNodeValue;

const date = dateEl.getAttribute("ISO");

CodePudding user response:

try this with camaro. test with runkit here https://runkit.com/embed/vxenbgqb1g7x

var { transform } = require("camaro")

var xml = `
<PARAGRAPH>
    This is a text, about something, that happened on 
    <DATE ISO="20131117">17.November 2013</DATE>
    . It is a very important date.
</PARAGRAPH>
`;

async function main() {
    console.log(await transform(xml, {iso: 'PARAGRAPH/DATE/@ISO'}))
}

main()

output

{iso: "20131117"}
  • Related