Селектор Nodejs xpath в xhtml не работает - PullRequest
0 голосов
/ 25 февраля 2019

У меня есть эта простая, но не очень хорошо отформатированная html-страница со всеми ее ошибками:

<HTML>
<head>
  <title>Official game sheet</title>
</head>
<body class="sheet">
</BODY>
</HTML>

Попытка применить заголовок xpath // к документу, проанализированному из этого html.

const document = parse5.parse(xmlString);
const xhtml = xmlser.serializeToString(document);
const doc = new dom().parseFromString(xhtml);
const select = xpath.useNamespaces({
  "x": "http://www.w3.org/1999/xhtml"
});
const nodes = select("//title", doc);
console.log(nodes);

Пробовал решение отсюда безуспешно.Список возвращенных узлов пуст.

Здесь вы можете увидеть проблему.

Ответы [ 2 ]

0 голосов
/ 25 февраля 2019

исправьте строки, чтобы получить заголовок

const nodes = select("//x:title//text()", doc);
console.log(nodes[0].data)
0 голосов
/ 25 февраля 2019

Вот, пожалуйста, @neptune, вам не нужны ни parse5, ни xmlser, все что нужно, это xpath и xmldom.

var xpath = require('xpath');
var dom = require('xmldom').DOMParser;
var xmlString = `
<HTML>
<head>
  <title>Official game sheet</title>
  <custom>Here we are</custom>
<body class="sheet">
</BODY>
</HTML>`;

//const document = parse5.parse(xmlString);
//const xhtml = xmlser.serializeToString(document);
const doc = new dom().parseFromString(xmlString);
const nodes = xpath.select("//custom", doc);
//console.log(document);

console.log(nodes[0].localName + ": " + nodes[0].firstChild.data);
console.log("Node: " + nodes[0].toString());
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...