Are line breaks in XML attribute values allowed?
Asked Answered
L

4

107

I realise that it's not elegant or desired, but is it allowed (in well-formed XML) for an attribute value in an XML element to span multiple lines?

e.g.

<some-xml-element value="this value goes over....
multiple lines!" />

Yeah I realise there's better ways of writing that. I would personally write it like:

<some-xml-element>
<value>this value goes over...
multiple lines!</value>
</some-xml-element>

or:

<some-xml-element value="this value goes over....&#13;&#10;" />

But we have our own XML parser and I'd like to know whether the first example is allowed in well-formed XML.

Limp answered 16/1, 2009 at 5:57 Comment(4)
The .NET XDocument parser accepts this as expected, but the attribute value is returned with a space, not a line feed as it would be in a text <value> as you second example. (Your question is not specific to .NET, but my sample data is. I don't know if this is part of the general standard or a .NET feature.)Azzieb
See also https://mcmap.net/q/205312/-how-to-save-newlines-in-xml-attribute/55452Choler
made an example to a similar question that preserves newlines: https://mcmap.net/q/205313/-preserving-attribute-whitespaceEatables
related: stackoverflow.com/questions/260436 - related: stackoverflow.com/questions/2004386 - related: stackoverflow.com/questions/1289524Eatables
M
110

http://www.w3.org/TR/REC-xml/#NT-AttValue

Seems to say everything except <, &, and your delimiter (' or ") are OK. So newline should be, too.

Magel answered 16/1, 2009 at 6:12 Comment(3)
One example when new lines are a good idea inside an attribute is for xsi:schemaLocation attribute in the Spring configuration, which can contain several URLs separated by spaces and thus be much longer than the screen width.Tahr
it is valid however the parser will normalize them to space, as Jan Cetkovsky says.Eatables
Well ... I use multiple lines for long if/when test statements in XSLT documents.Stylus
B
55

It is allowed, however according to W3C recommendation your XML parser should normalize the all whitespace characters to space (0x20) - so the output of your examples will differ (you should have new line on the output for "&#13;&#10;", but only space in the first case).

http://www.w3.org/TR/1998/REC-xml-19980210#AVNormalize

Brockington answered 18/11, 2011 at 19:51 Comment(0)
C
4

.NET only: If you're not sure if target string is valid xml attribute (and provide this attribute's value via code), you can always use SecurityElement.Escape function to escape invalid characters.

According to the description of this function, the only invalid characters are:

<, >, &, ', "

And this means (as my predecessors wrote), that new line should be OK.

Chose answered 15/11, 2011 at 9:38 Comment(0)
W
2

Yes the first example is a valid one.

Weatherboard answered 16/1, 2009 at 6:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.