我正在更新一个小的xml文件。输入在属性中包含换行符,如下所示:
<foo>
<add name="bar"
attr1="aaaa;
bbbbb;
cccc"/>
</foo>
然而,输出看起来像这样(带有 换行)
<foo>
<add name="bar" attr1="aaaa;
 bbbbb;
 cccc"/>
</foo>
我尝试了几种查找和删除换行符的方法。
解决方法是在输入中没有换行符。但是,为了便于阅读,我想在输入中留下换行符。我宁愿把它们留在输出中,但是,这不是必需的。
如何控制输出中的换行符,方法是让它们成为“真正的”换行符,还是删除它们?
以下是复制问题的测试程序;它没有数据更新,就像真正的例程一样。除了换行之外,真正的例程工作正常。
Sub Test()
On Error GoTo ErrTrap:
Dim XMLDoc As New MSXML2.DOMDocument60
Dim wrkInFolder As String
Dim wrkInFullPath As String
Dim wrkOutFolder As String
Dim wrkOutFullPath As String
Dim wrkCSNode As IXMLDOMNode
Dim wrkDataCS As IXMLDOMNode
Dim wrkAttr As IXMLDOMAttribute
Dim wrkInVal As String
Dim wrkOutVal As String
'---- set up the I/O Paths
wrkInFolder = "D:\mypath\"
wrkInFullPath = wrkInFolder & "xmltest.config"
wrkOutFolder = wrkInFolder
wrkOutFullPath = wrkOutFolder & "xmltest-out.config"
'---- get the doc
XMLDoc.Load (wrkInFullPath)
'--- get conn str node
Set wrkCSNode = XMLDoc.SelectSingleNode("foo")
'--- first child node (base 0)
Set wrkDataCS = wrkCSNode.ChildNodes(0)
'--- first attribute (base 0)
Set wrkAttr = wrkDataCS.Attributes(0)
'---- get the value of the attribute
wrkInVal = wrkAttr.NodeValue
wrkOutVal = Replace(wrkInVal, "
", "")
p1 = InStr(wrkOutVal, "
")
If p1 <> 0 Then
MsgBox ("Found line feed")
End If
wrkAttr.NodeValue = wrkOutVal
XMLDoc.Save (wrkOutFullPath)
On Error GoTo 0
Exit Sub
ErrTrap: Dim exmsg As String exmsg = Err.Description Dim wrkStop As String wrkStop =“” 错误转到0
End Sub
答案 0 :(得分:0)
你所指的实际上是空白,而不是换行。您可以使用XSLT重新设置XML。然后,使用XSLT的normalize-space()
函数处理属性值中的空格。
作为背景,XSLT是一种特殊用途的声明性语言,用于将XML转换/格式化为任何重组格式。在VBA中(与许多其他编程语言一样),您可以在外部加载XSLT(就像您的XML文件一样)或内联字符串。下面是外部文件路径:
XSLT (几乎是标识转换为克隆结构但删除了属性值中的空格)
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>
<xsl:template match="node()">
<xsl:copy>
<xsl:apply-templates select="@* | node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="@*">
<xsl:attribute name="{name()}">
<xsl:value-of select="normalize-space()"/>
</xsl:attribute>
</xsl:template>
</xsl:stylesheet>
VBA (在wrkInFolder中加载.config xml和.xsl文件并转换为输出的.config文件)
Dim XMLDoc As New MSXML2.DOMDocument60
Dim XSLDoc As New MSXML2.DOMDocument60
Dim OutputXML As New MSXML2.DOMDocument60
Dim wrkInFolder As String, wrkInFullPath As String
Dim wrkOutFolder As String, wrkOutFullPath As String
'---- Set up the I/O Paths
wrkInFolder = "D:\mypath\"
wrkInFullPath = wrkInFolder & "xmltest.config"
wrkOutFolder = wrkInFolder
wrkOutFullPath = wrkOutFolder & "xmltest-out.config"
'---- Load xml data
XMLDoc.async = False
XMLDoc.Load wrkInFullPath
'---- Load xslt stylesheet
XSLDoc.async = False
XSLDoc.Load wrkInFolder & "xslfile.xsl" ' SAVE ABOVE EXTERNALLY IN .xsl FORMAT
'---- Do the transform
XMLDoc.transformNodeToObject XSLDoc, OutputXML
OutputXML.Save wrkOutFullPath