您可以在XML中保留开头和结尾的空格吗? [英] Can you preserve leading and trailing whitespace in XML?

查看:348
本文介绍了您可以在XML中保留开头和结尾的空格吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何告诉XML解析器遵循前导和尾随空白?

How does one tell the XML parser to honor leading and trailing whitespace?

Dim xml: Set xml = CreateObject("MSXML2.DOMDocument")
xml.async = False
xml.loadxml "<xml>1 2</xml>"
wscript.echo len(xml.documentelement.text)

上面打印出3.

Dim xml: Set xml = CreateObject("MSXML2.DOMDocument")
xml.async = False
xml.loadxml "<xml> 2</xml>"
wscript.echo len(xml.documentelement.text)

上面打印出1.(我想打印2).

Above prints out 1. (I'd like it to print 2).

我可以在xml文档中放入一些特殊的内容来告诉解析器在文档中保留前导和尾随空白吗?

Is there something special I can put in the xml document itself to tell the parser to keep leading and trailing whitespace in the document?

说明1 :是否存在可以在文档开头指定一次的属性以应用于所有元素?

CLARIFICATION 1: Is there an attribute that can be specificed ONCE at the beginning of the document to apply to all elements?

澄清2 :由于实体的内容可能具有unicode数据,但是xml文件必须是纯ascii格式,因此所有实体均已编码-不幸的是,这意味着CDATA不可用.

CLARIFICATION 2: Because the contents of the entities may have unicode data, but the xml file needs to be plain ascii, all entities are encoded -- meaning CDATA's unfortunately are not available.

推荐答案

正如我评论的那样,所有建议使用xml:space="preserve"的答案都是错误的.

As I commented, all answers recommending the usage of the xml:space="preserve" are wrong.

xml:space属性只能用于控制仅用于空格的节点,即由文本完全组成的文本节点.

The xml:space attribute can only be used to control the treatment of whitespace-only nodes, that is text nodes composed entirely of whitespace characters.

当前问题根本不是这种情况.

This is not at all the case with the current problem.

实际上,下面提供的代码为包含在以下内容中的文本节点正确获取了2的长度:

In fact, the code provided below correctly obtains a length of 2 for the text node contained in:

<xml> 2</xml>

以下是正确获取文本节点长度的VB代码(不要忘记添加对"Microsoft XML,v 3.0"的引用):

Here is the VB code that correctly gets the length of the text node (do not forget to add a reference to "Microsoft XML, v 3.0"):

Dim xml As MSXML2.DOMDocument
Private Sub Form_Load()
Set xml = CreateObject("MSXML2.DOMDocument")
xml.async = False
xml.loadxml "<xml> 2</xml>"
Dim n
n = Len(xml.documentelement.selectSingleNode("text()").nodeValue)
wscript.echo Len(n)
End Sub

如果在行上放置断点:

wscript.echo Len(n)

您会看到,当调试器在此处中断时,n的值为2.

you'll see that when the debugger breaks there, the value of n is 2, as it is required.

因此,此代码是正在寻求的解决方案.

这篇关于您可以在XML中保留开头和结尾的空格吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆