28

I have some text, that is actually an XML snippet, which I want to display in an MS Word document. I really don't want to laboriously style every element and attribute by hand - is there some auto-style I can apply? Is there another solution?

4 Answers 4

45

You can use Notepad++. After installing:

  • Copy your XML to the Notepad++ window (in XML language mode)
  • Select the syntax highlighted XML you wish to post to Word
  • Select PLugins->NppExport->Copy RTF to Clipboard
  • Paste the formatted RTF into your word doc.
2
  • Unfortunately the colours don't come across
    – PeterX
    Feb 14, 2020 at 3:46
  • I've tended to use Copy HTML to Clipboard. But I've just discovered that the RTF option doesn't have all the annoyances of the HTML option. However, one annoyance remains: it insists on setting the style to Normal for the pasted text, regardless of the style already being used where I'm pasting it or anything else. If I reapply the style I want after pasting, I tend to lose one or two of the colours.
    – Stewart
    Dec 22, 2022 at 15:54
2

Use an external highlighter such as pygmentize to generate HTML, then copy and paste that into the document.

1

Create a new style that formats the XML the way you want. The style will likely need to include:

  • setting the font to a monospaced font like Courier New
  • setting the language to No Proofing (Word 2003 and older) or Do Not Check Spelling or Grammar (Word 2007 and newer)
  • setting the font size to something smaller; often XML or other code won't fit well on a page unless you make it smaller

To use this, select the XML text and change the style. All the formatting attributes will be applied at once.

The upside is that XML is text in the document. You can edit it like any other text if you need to make corrections; search for it, etc. The downside of this method is that syntax colouring won't be applied to the text unless it was already there when the text was pasted.

Save the style in the normal.dot template (the default) so that it's available in all documents.

If you need to do this often, you can assign a keyboard shortcut to the text so you don't have to select the style from the style menu.

1

Open the XML file in VS Code. Add an XML formatter plugin if you don't already have one. Text copied from VS Code will preserve its formatting; I believe it copies as RTF.

Pasting into Word preserves all the syntax highlighting and other colors (even the background color, which is noticeable if you're using dark mode) so it will look just like it did in VS Code. FYI this works great for pasting into Outlook too, and for other formats like JSON, YAML, or any type of code. If it looks good in VS Code, you can copy it that way and it will look good in Word/Outlook.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .