是否允许 XML 属性值中的换行符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/449627/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Are line breaks in XML attribute values allowed?
提问by CodeAndCats
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?
我意识到这并不优雅或不理想,但是否允许(在格式良好的 XML 中)XML 元素中的属性值跨越多行?
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.... " />
But we have our own XML parser and I'd like to know whether the first example is allowed in well-formed XML.
但是我们有自己的 XML 解析器,我想知道第一个示例是否允许在格式良好的 XML 中使用。
回答by derobert
http://www.w3.org/TR/REC-xml/#NT-AttValue
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.
似乎除了<,&和您的分隔符('或")之外的所有内容都可以。所以换行也应该是。
回答by Jan Cetkovsky
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 " ", but only space in the first case).
这是允许的,但是根据 W3C 的建议,您的 XML 解析器应该将所有空白字符规范化为空格 (0x20) - 因此您的示例的输出会有所不同(您应该在“ ;",但在第一种情况下只有空格)。
回答by ?ukasz Wiatrak
.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.Escapefunction to escape invalid characters.
仅限 .NET:如果您不确定目标字符串是否是有效的 xml 属性(并通过代码提供此属性的值),您始终可以使用SecurityElement.Escape函数来转义无效字符。
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.
这意味着(正如我的前任所写),新行应该没问题。
回答by Reji
Yes the first example is a valid one.
是的,第一个例子是一个有效的例子。

