DOM - 在java

时间:2015-12-05 14:18:23

标签: java xml parsing dom xml-parsing

我有一个包含许多<dict>元素的xml文件,我想尝试获取第三个元素中的元素。我的问题是,当我调用doc.getElementsByTagName(“dict”)时,它会获取所有被称为dict的元素。

以下是代码:

try {
        File inputFile = new File("itunes2.xml");
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory
                .newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(inputFile);
        doc.getDocumentElement().normalize();
        System.out.println("Root element :"
                + doc.getDocumentElement().getNodeName());
        NodeList nList = doc.getElementsByTagName("dict");
        System.out.println("----------------------------");
        for (int temp = 0; temp < nList.getLength(); temp++) {
            Node nNode = nList.item(temp);
            System.out.println("\nCurrent Element :" + nNode.getNodeName());
            if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                Element eElement = (Element) nNode;
                System.out.println("Major Version : "
                        + eElement.getElementsByTagName("integer").item(0)
                                .getTextContent());
                System.out.println("Minor Version : "
                        + eElement.getElementsByTagName("integer").item(0)
                                .getTextContent());
                System.out.println("Application version : "
                        + eElement.getElementsByTagName("string").item(0)
                                .getTextContent());
                System.out.println("Features : "
                        + eElement.getElementsByTagName("integer").item(2)
                                .getTextContent());
                System.out.println("Music Folder : "
                        + eElement.getElementsByTagName("string").item(1)
                                .getTextContent());
                System.out.println("Library Persistent ID : "
                        + eElement.getElementsByTagName("string").item(2)
                                .getTextContent());
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

XML:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Major Version</key><integer>1</integer>
<key>Minor Version</key><integer>1</integer>
<key>Application Version</key><string>10.1</string>
<key>Features</key><integer>5</integer>
<key>Show Content Ratings</key><true/>
<key>Music Folder</key><string>file://localhost//Thomts/Holly/data/My%20Music/iTunes/iTunes%20Music/</string>
<key>Library Persistent ID</key><string>29E12A03204E0721</string>
<key>Tracks</key>
<dict>
    <key>324</key>
    <dict>
        <key>Track ID</key><integer>324</integer>
        <key>Name</key><string>Talk Dirty To Me</string>
        <key>Artist</key><string>Poison</string>
        <key>Composer</key><string>Poison</string>
        <key>Album</key><string>The Best Of Poison: 20 Years Of Rock</string>
        <key>Genre</key><string>Metal</string>
        <key>Kind</key><string>AAC audio file</string>
        <key>Size</key><integer>3698203</integer>
        <key>Total Time</key><integer>224866</integer>
        <key>Disc Number</key><integer>1</integer>
        <key>Disc Count</key><integer>1</integer>
        <key>Track Number</key><integer>1</integer>
        <key>Track Count</key><integer>18</integer>
        <key>Year</key><integer>1986</integer>
        <key>Date Modified</key><date>2008-08-07T15:16:57Z</date>
        <key>Date Added</key><date>2008-08-07T15:17:17Z</date>
        <key>Bit Rate</key><integer>128</integer>
        <key>Sample Rate</key><integer>44100</integer>
        <key>Play Count</key><integer>6</integer>
        <key>Play Date</key><integer>3378486192</integer>
        <key>Play Date UTC</key><date>2011-01-22T03:23:12Z</date>
        <key>Compilation</key><true/>
        <key>Sort Album</key><string>Best Of Poison: 20 Years Of Rock</string>
        <key>Persistent ID</key><string>29E12A03204E0873</string>
        <key>Track Type</key><string>File</string>
        <key>Location</key><string>file://localhost//Thomts/Holly/data/My%20Music/iTunes/iTunes%20Music/Compilations/The%20Best%20Of%20Poison_%2020%20Years%20Of%20Rock/01%20Talk%20Dirty%20To%20Me.m4a</string>
        <key>File Folder Count</key><integer>4</integer>
        <key>Library Folder Count</key><integer>1</integer>
    </dict>

它输出:

Root element :plist

Current Element :dict
Major Version : 1
Minor Version : 1
Application version : 10.1
Features : 5
Music Folder :  file://localhost//Thomts/Holly/data/My%20Music/iTunes/iTunes%20Music/
Library Persistent ID : 29E12A03204E0721

Current Element :dict
Major Version : 324
Minor Version : 324
Application version : Talk Dirty To Me
Features : 224866
Music Folder : Poison
Library Persistent ID : Poison

正如您所看到的,它获取了第一个元素的正确信息,然后是第二个元素的错误信息。我想知道如何在第三个dict标签中获取所有信息,以便我可以获得歌曲的所有信息,例如曲目ID,姓名,艺术家等..

1 个答案:

答案 0 :(得分:0)

你不能提取好的信息,首先是因为它们之间没有联系:

例如:主要版本1

检索:整数,而不是按键

您必须测试密钥的第一个内容,然后采用下一个项目(整数)。

否则,如果可以选择xml文件的格式,

你应该通过密钥检索,并将1放在这个标签内,就像那样

&LT;键名=&#34;主要版本&#34;&gt;&lt;整数&GT; 1&lt; / integer&gt;&lt; /键&GT;

或只是&lt;键名=&#34;主要版本&#34;&gt; 1&lt; /键&GT;如果你不关心类型信息

或&lt; Major_Version→1&LT; / Major_Version&GT; :你可以通过

进行检索
getElementsByTagName("Major_Version")

我重写了你的代码:

你也应该对专辑的dict和歌曲的dict(不同的键可用)有所区别。

NodeList nList = document.getElementsByTagName("dict");
System.out.println("----------------------------");
for (int temp = 0; temp < nList.getLength(); temp++) 
    {
    Node nNode = nList.item(temp);

    if (nNode.getNodeType() == Node.ELEMENT_NODE)
        {
        Element eElement = (Element) nNode;

        System.out.println("NODE NAME:"+eElement.getNodeName());
        System.out.println("TAG NAME:"+eElement.getTagName());

        // Iterate through sub-elements

        // A map to store key => values
        Map<String,String> mss=new HashMap<String,String>();

        NodeList childs = eElement.getChildNodes();
        {
             for (int k = 0; k < childs.getLength(); k++) 
            {
             Node child = childs.item(k);

             if (child.getNodeType() == Node.ELEMENT_NODE)
                {
                 Element child_element = (Element) child;
                 String tag=child_element.getTagName();
                 String content=child_element.getTextContent();

                 if (tag.equals("key") && (k+1< childs.getLength()))
                 {
                // Next one
                    Node next = childs.item(k+1);

                    if (next.getNodeType() == Node.ELEMENT_NODE)
                    {
                     Element next_element = (Element) next;
                     // Should be integer or string
                     String next_tag=next_element.getTagName();
                     String next_content=next_element.getTextContent();

                     // store
                     mss.put(content, next_content);
                     // skip
                     k++;
                    }
                 }
                }
            }
        }

        // SEE THE MAP
        System.out.println("ALL ELEMENTS:"+mss);

        // Get what you want
        String major_version="";
        String minor_version="";
        String application_version="";
        String music_folder="";
        String track_id="";
        String name="";
        String artist="";

        if (mss.containsKey("Major Version")) major_version=mss.get("Major Version");
        if (mss.containsKey("Minor Version")) minor_version=mss.get("Minor Version");
        if (mss.containsKey("Application Version")) application_version=mss.get("Application Version");
        if (mss.containsKey("Music Folder")) music_folder=mss.get("Music Folder");
        if (mss.containsKey("Track ID")) track_id=mss.get("Track ID");
        if (mss.containsKey("Name")) name=mss.get("Name");
        if (mss.containsKey("Artist")) artist=mss.get("Artist");

        // SHOW
        System.out.println("Major  Version : "+major_version);
        System.out.println("Minor Version : "+minor_version);
        System.out.println("Application version : "+application_version);
        System.out.println("Music Folder : "+music_folder);          

        System.out.println("Track ID : "+track_id);   
        System.out.println("Name : "+name);   
        System.out.println("Artist : "+artist); 
        }
    }

我希望它可以帮到你