在Word中使用VBA进行CustomXML提取

时间:2013-07-04 14:15:05

标签: xml vba ms-word

我在Word文档中有一些CustomXML数据,我试图在VBA中引用它。我已经加载了XML部分,但无法获得具体的值。

XML:

    <?xml version="1.0"?>
<?mso-infoPathSolution solutionVersion="1.0.0.3" productVersion="14.0.0" PIVersion="1.0.0.0" href="http://portal-mysites/personal/adamh/Personal%20Documents/PropTest.xsn" name="urn:schemas-microsoft-com:office:infopath:PropTest:-myXSD-2013-07-01T14-47-53" ?>
    <?mso-application progid="InfoPath.Document" versionProgid="InfoPath.Document.3"?>
    <my:myFields xmlns:my="http://schemas.microsoft.com/office/infopath/2003/myXSD/2013-07-01T14:47:53">
      <my:tCompany>AnyCharity</my:tCompany>
      <my:tCharity>true</my:tCharity>
      <my:tEthernet>false</my:tEthernet>
      <my:tContact>ANOther</my:tContact>
    </my:myFields>

宏代码:

 Sub TestPropMac()
    Dim myPart As CustomXMLPart
    Dim oNode As CustomXMLNode
    Set myPart = GetXMLPartByRoot_Element(ActiveDocument, "myFields")
    MsgBox myPart.XML
    Set oNode = myPart.SelectSingleNode("myFields/tCharity")
    MsgBox oNode.NodeValueEnd Sub

我正在使用MsgBox来确认我已经到达了数据(我没有) - 我打算对另一个函数的值使用If语句。

1 个答案:

答案 0 :(得分:0)

你没有显示GetXMLPartByRoot_Element的代码(它不在Word对象模型AFAIK中),但你需要更像这样的东西:

Sub TestPropMac()
    Const ns As String = "http://schemas.microsoft.com/office/infopath/2003/myXSD/2013-07-01T14:47:53"
    Dim myParts As CustomXMLParts
    Dim oNode As CustomXMLNode
    Dim strPrefix As String

    Set myParts = ActiveDocument.CustomXMLParts.SelectByNamespace(ns)
    MsgBox myParts(1).XML
    strPrefix = myParts(1).NamespaceManager.LookupPrefix(ns) & ":"
    Set oNode = myParts(1).SelectSingleNode(strPrefix & "myFields" & "/" & strPrefix & "tCharity")
    MsgBox oNode.Text
    Set oNode = Nothing
    Set myParts = Nothing
End Sub

strPrefix不是“my:”,而是Word生成的前缀名称,例如“ns0:”