从XML解析键/值对

时间:2014-05-02 09:42:46

标签: xml vbscript xml-parsing key-value

我正在寻找解析iTunes Library XML文件中的一些数据,为此我希望在VBScript中有一个优雅的解决方案来解析键/值对。这是XML结构:

<plist version="1.0">
    <dict>
        <dict>
            <key>1</key>
            <dict>
                <key>Location</key><string>"file1.mp3"</string>
            </dict>
            <key>2</key>
            <dict>
                <key>Location</key><string>"file2.mp3"</string>
            </dict>
        </dict>
    </dict>
</plist>

我现在只列出了两个键/值(<key>/<dict>)对,但当然有很多。

我想把它解析成某种字典对象,如下所示:

1 file1.mp3
2 file2.mp3

我可以想出一些方法来实现这一点,比如涉及NextSibling()方法,但这对我来说真的太过分了。

那么这个问题的官方/优雅解决方案是什么?提前谢谢!

1 个答案:

答案 0 :(得分:0)

我会搜索位置,然后使用家庭关系来获取密钥和文件。在代码中:

  Dim oFS      : Set oFS      = CreateObject("Scripting.FileSystemObject")
  Dim sFSpec   : sFSpec       = goFS.GetAbsolutePathName("..\testdata\xml\so23425116.xml")
  Dim objMSXML : Set objMSXML = CreateObject("Msxml2.DOMDocument")
  objMSXML.setProperty "SelectionLanguage", "XPath"
  objMSXML.async = False
  objMSXML.load sFSpec

  If 0 = objMSXML.parseError Then
     Dim sXPath : sXPath     = "/plist/dict/dict/dict/key[. = ""Location""]"
     Dim ndlFnd : Set ndlFnd = objMSXML.selectNodes(sXPath)
     If 0 = ndlFnd.length Then
        WScript.Echo sXPath, "not found"
     Else
        Dim dicKV : Set dicKV = CreateObject("Scripting.Dictionary")
        Dim ndFnd, ndLoc, ndKey
        For Each ndFnd In ndlFnd
            Set ndLoc = ndFnd.nextSibling
            Set ndKey = ndFnd.parentNode.previousSibling
            WScript.Echo ndKey.text, ndLoc.text
            dicKV(ndKey.text) = ndLoc.text
        Next
        WScript.Echo "------------"
        Dim sKey
        For Each sKey In dicKV
            WScript.Echo sKey, dicKV(sKey)
        Next
     End If
  Else
     WScript.Echo objMSXML.parseError.reason
  End If

示例输出(对于样本.xml的变体):

1 "file1.mp3"
2 "file2.mp3"
290 file://localhost/D:/iTunes/Bob%20Russell%20Sermons/Sermons/1999/01-03%20Good%20News.mp3
------------
1 "file1.mp3"
2 "file2.mp3"
290 file://localhost/D:/iTunes/Bob%20Russell%20Sermons/Sermons/1999/01-03%20Good%20News.mp3

免责声明:

  • 我不使用iTunes,所以我不确定随机选择2 我用于测试的样本.xml非常具有代表性。
  • 文件规格显然需要一些清理