2

I am using xmlbuilder2 to create an XML document from a JS object.

This works just fine:

const { create } = require('xmlbuilder2');

const obj = {
  root: {
    '@att': 'val',
    foo: {
      bar: 'foobar'
    },
    baz: {}
  }
};

const doc = create(obj);
const xml = doc.end({ prettyPrint: true });
console.log(xml);

However, I want to get the following XML:

<?xml version="1.0"?>
<root att="val">
  <foo>
    <bar myattr="hello">foobar</bar>
  </foo>
  <baz/>
</root>

How do I set both the attribute and content for the bar element? I did not find any examples online, I've tried using @text but it didn't work.

Thanks!

2

1 Answer 1

1

I figured it out (with the help of Tomalak!) that the correct way is to do:

const { create } = require('xmlbuilder2');

const obj = {
  root: {
    '@att': 'val',
    foo: {
      bar: {"@myattr":"hello", "#":'foobar'}
    },
    baz: {}
  }
};

const doc = create(obj);
const xml = doc.end({ prettyPrint: true });
console.log(xml);
Sign up to request clarification or add additional context in comments.

Comments

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.