我需要删除XML中的节点,我的XML如下所示
<message_version>Test</message_version>
<responder_id>My test XML file</responder_id>
</m_control>
<m_content>
<b_control>
<quote_response_status>error</quote_response_status>
<quote_error_note>
<reason>
<note>
<text>An error occurred.
</text>
</note>
</reason>
</quote_error_note>
</b_control>
在上面的xml中我需要删除节点“text”和“note”,同时保留文本“发生错误”。不变。我怎样才能做到这一点。
基本上我在删除节点'text'和'note'
之后需要一个XML<message_version>Test</message_version>
<responder_id>My test XML file</responder_id>
</m_control>
<m_content>
<b_control>
<quote_response_status>error</quote_response_status>
<quote_error_note>
<reason>
An error occurred.
</reason>
</quote_error_note>
</b_control>
我尝试了以下但没有成功:
sXMLPath = "//message/m_content/b_control/quote_error_note/reason"
Set sRemoveText = m_objResponseXML.selectSingleNode(sXMLPath & "/note/text")
Set sRemoveNote = m_objResponseXML.selectSingleNode(sXMLPath & "/note")
If Not sRemoveText is Nothing Then
m_objResponseXML.selectSingleNode(sXMLPath & "/note").removeChild(sRemoveText)
sErrorMsg = GetNodeText(sXMLPath & "/note/text", m_objResponseXML)
End if
If Not sRemoveText is Nothing Then
m_objResponseXML.selectSingleNode(sXMLPath).removeChild(sRemoveNote)
End If
If sErrorMsg <> "" Then
m_objResponseXML.selectSingleNode(sXMLPath).text = sErrorMsg
End If
非常感谢任何形式的帮助。
答案 0 :(得分:2)
用代码来说明Rafael的建议,并在阅读文档时为您提供一些搜索/关键字:
Option Explicit
Dim oXML : Set oXML = CreateObject("MSXML2.DomDocument")
If oXML.load(".\005.xml") Then
WScript.Echo oXML.xml
Dim ndReason : Set ndReason = oXML.selectSingleNode("/b_control/quote_error_note/reason")
If ndReason Is Nothing Then
WScript.Echo "not reasonable"
Else
Dim sReason : sReason = ndReason.selectSingleNode("note/text").text
ndReason.removeChild ndReason.firstChild
WScript.Echo oXML.xml
ndReason.appendChild oXML.createTextNode(sReason)
WScript.Echo oXML.xml
End If
Else
WScript.Echo oXML.parseError.reason
End If
输出:
cscript 005.vbs
<b_control>
<quote_response_status>error</quote_response_status>
<quote_error_note>
<reason>
<note>
<text>An error occurred.
</text>
</note>
</reason>
</quote_error_note>
</b_control>
<b_control>
<quote_response_status>error</quote_response_status>
<quote_error_note>
<reason>
</reason>
</quote_error_note>
</b_control>
<b_control>
<quote_response_status>error</quote_response_status>
<quote_error_note>
<reason>An error occurred.</reason>
</quote_error_note>
</b_control>
答案 1 :(得分:0)
以您希望的方式删除数据,违反XML / HTML Hierarchy原则,其中每个标记都包含在另一个标记中。
简单的解决方案是复制字符串删除标签并填充reason标签的text属性来实现这一点。
其他方式,将是邪恶
操纵XML,您可以使用MSXML Object Reference
基于显示的示例
sXMLPath = "//message/m_content/b_control/quote_error_note/reason"
您的XPath字符串不正确正确
sXMLPath = "//b_control/quote_error_note/reason"