2013-07-04 22 views
3

我想在VBA中引用一个Word文档中的一些CustomXML数据。我已经加载XML部分,但无法获得具体的价值。在Word中使用VBA的CustomXML提取

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确认我已经达到的数据(我没有) - 我打算使用如果声明反对另一个函数的值。

+0

嗨!欢迎来到!你想要弄清什么具体数据?你可能想看到这个:http://stackoverflow.com/questions/11305/how-to-parse-xml-in-vba使用if语句和VBA的常规字符串匹配来解析XML之类的东西是一个很大的禁忌,尽管。 – franklin

+0

例如,我想检查tCharity的值(当前为true) - 这将链接到InfoPath表单中的复选框,所以如果勾选框,则采取一个操作,如果不是,则采取不同的操作。 – AdamHw

+0

我看到了......说实话,做这件事的“最好”方法可能是引用MSXML库a/k/a microsft核心xml API。它具有处理XML数据结构很有用的各种东西。但是,如果你想快速和肮脏,你只需要一个领域,那么也许调用微软的内置regexp包就足够了。你可以在这里阅读更多。 http://www.regular-expressions.info/vb.html我知道我以后会在这个方向引发你的火灾......但有时候解决这个问题是“足够好” – franklin

回答

0

你不显示GetXMLPartByRoot_Element代码(这不是在Word对象模型中据我所知),但你需要更多的东西是这样的:

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不会是“我的”,但会一个Word生成的前缀名称,如“ns0:”

+0

嘿,我面临类似的情况,但我使用的是C#,并且在C#中不能使用CustomXMLParts(myParts)作为方法。也没有.item方法。有关于此的任何帮助? –

+1

我认为,取决于C#和Framework的版本,但您可能需要获取对.doc的引用,然后使用.CustomXMLParts [index]来获取单个部分。 – 2014-05-27 15:55:58