Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

xml - How to parse .plist file in Java?

I am trying to parse a .plist file in Java but not understanding how. I used a DOM parser but it gives an error and is not able to read .plist file.

This is my plist file:

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>

This my main function:

 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();
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If I were you I'd use the PList class from code.google.com/xmlwise. It's specifically designed for dealing with .plist files.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...