Search code examples
ms-wordoffice-jsword-addins

What does `namespaceMappings` mean in Word.CustomXMLPart API


I have created a small snippet in Script Lab which basically:

  1. Creates a custom XML:
<AP xmlns="accordproject.org">
  <template xmlns="acceptance-of-delivery">
    <shipper>Aman Sharma</shipper>
  </template> 
</AP>
  1. Tries to query this xml by using the xPath /AP/template. I run this block of code:
await Word.run(async context => {
  const customXmlParts = context.document.customXmlParts;
  const AP = customXmlParts.getByNamespace("accordproject.org").getOnlyItemOrNullObject();
  await context.sync();
  const nodes = AP.query('/AP/template', {}); // how does this work?
  await context.sync();
  console.log(nodes);
})
  1. Deletes the customXML.

The second argument of query API is namespaceMappings. I think I am passing that incorrectly and that's why I get this as ouput (empty object). empty array

But when I pass * instead of /AP/template, I get the whole XML (while the second argument, namespaceMappings remain the same).

Where am I going wrong? Can anyone share some snippets to help me query customXML.


Solution

  • The short answer is that you can use

    const nodes = AP.query("/n1:AP/n2:template", {n1:"accordproject.org", n2:"acceptance-of-delivery"});
    

    I don't know JS/TS at all but I assume these are basically key-value pairs of some kind. You can also use

    const nodes = AP.query("/n1:AP/n2:template", {"n1":"accordproject.org", "n2":"acceptance-of-delivery"});
    

    if you prefer to think of the Namespace prefixes as strings.

    (For anyoneunfamiliar, the "n1" and "n2" are just prefixes that you invent so you can reference the full Namespace URIs. They don't have anything to do with any prefixes you might have used in the piece of XML you are querying.)

    I couldn't find documentation on this either and originally assumed you might need something more like { Prefix:"ns1", namespaceURI:"the namespace URI" }, but that's just because those are the property names used in the VBA model.