0

I'm trying to check if a pair (element, value) exists in XML. I'm using xmldoc

XML file:

<?xml version="1.0"?>
<listings>
    <listing>
        <id>1</id>
        <name>TEST1</name>
        <description>TEST1</description>
    </listing>
    <listing>
        <id>2</id>
        <name>TEST</name>
        <description>TEST</description>
    </listing>
</listings>

My code:

const fs = require('fs');
const path = require("path");
const xmldoc = require('xmldoc');

const xml = fs.readFileSync(path.resolve(__dirname, "./myXML"), 'utf8');
const doc = new xmldoc.XmlDocument(xml);
const check = doc.childWithAttribute('id', '2');
console.log(check);

It's returning undefined, but I have an element with the id = 2.

Does anyone know what I am doing wrong? Also, after finding the element, is it possible to delete it?

Thanks

4
  • As per docs the childWithAttribute function Searches for the first child with the given attribute value.. I assume this means it will not recursively search through your doc. You will have to create the code to check the deeper levels Commented Jan 18, 2021 at 21:11
  • I realize now that you're actually not looking for an attribute but for a whole name... try childNamed Commented Jan 18, 2021 at 21:17
  • You're going to have to use github.com/nfarina/xmldoc#eachchildfunc and search through it's children I think Commented Jan 18, 2021 at 21:27
  • Got it. Thank you Commented Jan 18, 2021 at 22:07

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.