0

I need to write <name> Dolce & Gabanna </name> in an xml file using java. However, what gets generated is <name> Dolce &amp; Gabanna </name>.

Is there any method I can use in java so "&" will be displayed in xml, instead of "&amp;"?

Thanks.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
Isiah
  • 95
  • 1
  • 7

1 Answers1

3

I need to write <name> Dolce & Gabanna </name> in an xml file using java.

No, you don't. Not unless you're trying to create an invalid file. Whatever code you're using is doing exactly the right thing - any XML parser reading the file will then unescape the &amp; to & where appropriate.

From the XML 1.0 specification, section 2.4:

The ampersand character (&) and the left angle bracket (<) must not appear in their literal form, except when used as markup delimiters, or within a comment, a processing instruction, or a CDATA section. If they are needed elsewhere, they must be escaped using either numeric character references or the strings " &amp; " and " &lt; " respectively.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 1
    Would there be a way to display "&" if it is an invalid XML file? It doesn't matter to me if xml is valid or invalid because it will not be parsed, i only need the raw xml file. – Isiah Jun 25 '15 at 17:17
  • 1
    @Isiah: Without the escaping, it *isn't* an XML file - not a valid one. You really need to decide whether you want valid XML, in which case you'll have `&`, or plain text, in which case why bother with XML at all? Going for some sort of half-way house is a really bad idea. – Jon Skeet Jun 25 '15 at 17:18
  • If it doesn't matter to you whether the file is valid or invalid, then why do you refer to it as "XML"? What are you actually going to do with this non-XML file that you want to produce? – Michael Kay Jun 25 '15 at 21:52