XML 属性值中是否允许换行?

我意识到它并不优雅或理想,但是允许 XML 元素中的属性值跨越多行吗(在格式良好的 XML 中) ?

例如:。

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

是的,我知道有更好的写法,我个人会这样写:

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

或:

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

但是我们有自己的 XML 解析器,我想知道在格式良好的 XML 中是否允许第一个示例。

65574 次浏览

Yes the first example is a valid one.

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.

.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.

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