如何使用excel vba 2007在xml中添加图像标记

时间:2013-01-27 15:10:33

标签: xml image vba excel-vba excel

我使用excel 2007 vba生成xml。执行宏后,我得到了这个输出 enter image description here

但我需要输出

enter image description here

我不想& lt和& gt而不是<和>标签。 我正在使用的宏是

enter code here

Dim xmlDoc As New MSXML2.DOMDocument30
Dim objNode As MSXML2.IXMLDOMNode
Dim personNode As MSXML2.IXMLDOMNode
Dim imagesNode As MSXML2.IXMLDOMNode
Set objNode = xmlDoc.createNode(NODE_PROCESSING_INSTRUCTION, "xml", "")
xmlDoc.appendChild objNode
Set objNode = xmlDoc.createNode(NODE_ELEMENT, "root", "")
Set personNode = xmlDoc.createNode(NODE_ELEMENT, "person", "")
objNode.appendChild personNode
Set imagesNode = xmlDoc.createNode(NODE_ELEMENT, "images", "")
personNode.appendChild imagesNode
imagesNode.Text = "<image href=" & Chr(34) & "file:///Users/d.jahr/Desktop/XML           Booklet/Bilder/pic1.jpg" & Chr(34) & "/>"
xmlDoc.appendChild objNode
Set objNode = Nothing
MsgBox xmlDoc.XML
xmlDoc.Save ActiveWorkbook.Path & "\" & "result.xml"

End Sub

请帮帮我。

由于

1 个答案:

答案 0 :(得分:1)

不是设置images集合的文本,而是考虑附加image子节点并设置它的href属性:

Sub test()
    Dim xmlDoc As New MSXML2.DOMDocument30
    Dim objNode As MSXML2.IXMLDOMNode
    Dim personNode As MSXML2.IXMLDOMNode
    Dim imagesNode As MSXML2.IXMLDOMNode

    Dim image1Node As MSXML2.IXMLDOMNode
    Dim namedItem As Object

    Set objNode = xmlDoc.createNode(NODE_PROCESSING_INSTRUCTION, "xml", "")
    xmlDoc.appendChild objNode
    Set objNode = xmlDoc.createNode(NODE_ELEMENT, "root", "")
    Set personNode = xmlDoc.createNode(NODE_ELEMENT, "person", "")
    objNode.appendChild personNode
    Set imagesNode = xmlDoc.createNode(NODE_ELEMENT, "images", "")
    personNode.appendChild imagesNode

    Set image1Node = xmlDoc.createNode(NODE_ELEMENT, "image", "")
    imagesNode.appendChild image1Node
    Set namedItem = xmlDoc.createAttribute("href")
    namedItem.Value = "file:///Users/d.jahr/Desktop/XMLBooklet/Bilder/pic1.jpg"
    image1Node.Attributes.setNamedItem namedItem

    xmlDoc.appendChild objNode
    Debug.Print xmlDoc.XML
End Sub

输出:

<?xml version="1.0"?>
<root>
   <person>
      <images>
         <image href="file:///Users/d.jahr/Desktop/XMLBooklet/Bilder/pic1.jpg"/> 
      </images>
   </person>
</root>