如何用Java解析.plist文件?

时间:2011-09-20 11:10:03

标签: java xml plist

我试图用Java解析.plist文件但不了解如何。我使用了DOM解析器,但是它出错并且无法读取.plist文件。

这是我的plist文件:

xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"                                                                    "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>All Samples</key>
<array>
    <dict>
        <key>Message</key>
        <string>1) UIATarget </string>
        <key>Timestamp</key>
        <date>2011-07-06T19:40:09Z</date>
        <key>Type</key>
        <integer>0</integer>
    </dict>

我的main函数:

 public static void main(String[] args) throws XMLStreamException, IOException {
    InputStream in = new FileInputStream("File.plist");
    XMLInputFactory factory = XMLInputFactory.newInstance();
    XMLEventReader parser = factory.createXMLEventReader(in);

    assert parser.nextEvent().isStartDocument();

    XMLEvent event = parser.nextTag();
    //System.out.println(event.getClass());
    assert event.isStartElement();
    final String name1 = event.asStartElement().getName().getLocalPart();

    if (name1.equals("dict")) {
        while ((event = parser.nextTag()).isStartElement()) {
            final String name2 = event.asStartElement().getName().getLocalPart();

            if (name2.equals("key")) {
                String key = parser.getElementText();
                System.out.println("key: " + key);

            } else if (name2.equals("String")) {
                String number = parser.getElementText();
                System.out.println("date: " + number);

            } else if (name2.equals("date")) {
                String str = parser.getElementText();
                System.out.println("date: " + str);
            }
        }
    }

    assert parser.nextEvent().isEndDocument();
}

3 个答案:

答案 0 :(得分:7)

如果我是你,我会使用PList中的code.google.com/xmlwise课程。它专门用于处理.plist文件。

答案 1 :(得分:1)

您需要查看http://commons.apache.org/proper/commons-configuration/上的Apache Commons Configuration,它提供了一个pList解析器。这是一个片段示例:

        XMLPropertyListConfiguration plist = new XMLPropertyListConfiguration();
        // load plist from classoath
        URL url = this.getClass().getClassLoader().getResource(systemConfigFile);
        plist.setFileName(url.getFile());
        plist.load();
        Iterator<String> keys = plist.getKeys();
        while (keys.hasNext()) {
            // do someting with the value
            plist.getString(keys.next());
        }

答案 2 :(得分:0)

github 上还有另一个项目可以直接访问基于 Maven 的项目:https://github.com/3breadt/dd-plist