从XML文件中提取值使用XPath,SAX或DOM进行此特定方案

时间:2012-10-28 09:15:30

标签: java xml dom xpath sax

我目前正在开展一个学术项目,在JavaXML开展。实际任务是解析XML,最好在HashMap中传递所需的值以进行进一步处理。这是实际XML的简短片段。

<root>
  <BugReport ID = "1">
    <Title>"(495584) Firefox - search suggestions passes wrong previous result to form history"</Title>

    <Turn>
      <Date>'2009-06-14 18:55:25'</Date>
      <From>'Justin Dolske'</From>
      <Text>
        <Sentence ID = "3.1"> Created an attachment (id=383211) [details] Patch v.2</Sentence>
        <Sentence ID = "3.2"> Ah. So, there's a ._formHistoryResult in the....</Sentence>
        <Sentence ID = "3.3"> The simple fix it to just discard the service's form history result.</Sentence>
        <Sentence ID = "3.4"> Otherwise it's trying to use a old form history result that no longer applies for the search string.</Sentence>
      </Text>
    </Turn>

    <Turn>
      <Date>'2009-06-19 12:07:34'</Date>
      <From>'Gavin Sharp'</From>
      <Text>
        <Sentence ID = "4.1"> (From update of attachment 383211 [details])</Sentence>
        <Sentence ID = "4.2"> Perhaps we should rename one of them to _fhResult just to reduce confusion?</Sentence>
      </Text>
    </Turn>

    <Turn>
      <Date>'2009-06-19 13:17:56'</Date>
      <From>'Justin Dolske'</From>
      <Text>
        <Sentence ID = "5.1"> (In reply to comment #3)</Sentence>
        <Sentence ID = "5.2"> &amp;gt; (From update of attachment 383211 [details] [details])</Sentence> 
        <Sentence ID = "5.3"> &amp;gt; Perhaps we should rename one of them to _fhResult just to reduce confusion?</Sentence>
        <Sentence ID = "5.4"> Good point.</Sentence>
        <Sentence ID = "5.5"> I renamed the one in the wrapper to _formHistResult. </Sentence>
        <Sentence ID = "5.6"> fhResult seemed maybe a bit too short.</Sentence>
      </Text>
    </Turn>

  .....
  and so on
</BugReport>

有很多评论家喜欢'Justin Dolske'评论过这份报告,我真正想要的是评论者列表以及他们在整个XML文件中写的所有句子。像if(from == justin dolske) getHisAllSentences()这样的东西。对于其他评论者(对所有人)也是如此。我尝试了很多不同的方法来获取“Justin dolske”或其他评论者的句子,即使是使用XPathSAXDOM的所有人的通用形式,但都失败了。我对这些技术都很陌生,包括JAVA以及任何不知道如何实现它的技术。

任何人都可以具体指导我如何使用上述任何技术获得它,或者还有其他更好的策略吗?

(注意:稍后我想把它放在hashmap中,例如像HashMap (key, value)其中key = name评论者(justin dolske)和值是(所有句子))

紧急帮助将受到高度赞赏。

2 个答案:

答案 0 :(得分:1)

我建议使用JAXB创建反映XML结构的数据模型。

完成后,您可以将XML加载到Java实例中。

使用Map< String, List< Turn >>作为关键字,将每个'转弯'放入Turn.From

完成后,您可以写:

List< Turn > justinsTurn = allTurns.get( "'Justin Dolske'" );

答案 1 :(得分:1)

有几种方法可以满足您的要求。

  • 一种方法是使用JAXB。网上有几个可用的教程,请随时参考。

  • 您还可以考虑创建DOM,然后从中提取数据,然后将其放入HashMap中。

一个参考实现将是这样的:

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;

import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

public class XMLReader {

    private HashMap<String,ArrayList<String>> namesSentencesMap;

    public XMLReader() {
        namesSentencesMap = new HashMap<String, ArrayList<String>>();
    }

    private Document getDocument(String fileName){
        Document document = null;

        try{
            document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File(fileName));
        }catch(Exception exe){
            //handle exception
        }

        return document;
    }

    private void buildNamesSentencesMap(Document document){
        if(document == null){
            return;
        }

        //Get each Turn block
        NodeList turnList = document.getElementsByTagName("Turn");
        String fromName = null;

        NodeList sentenceNodeList = null;
        for(int turnIndex = 0; turnIndex < turnList.getLength(); turnIndex++){
            Element turnElement = (Element)turnList.item(turnIndex);
            //Assumption: <From> element
            Element fromElement = (Element) turnElement.getElementsByTagName("From").item(0); 
            fromName = fromElement.getTextContent();
            //Extracting sentences - First check whether the map contains 
            //an ArrayList corresponding to the name. If yes, then use that,  
            //else create a new one                                              
            ArrayList<String> sentenceList = namesSentencesMap.get(fromName);
            if(sentenceList == null){
                sentenceList = new ArrayList<String>();
            }
            //Extract sentences from the Turn node
            try{
                sentenceNodeList = turnElement.getElementsByTagName("Sentence");
                for(int sentenceIndex = 0; sentenceIndex < sentenceNodeList.getLength(); sentenceIndex++){
                    sentenceList.add(((Element)sentenceNodeList.item(sentenceIndex)).getTextContent());
                }
            }finally{
                sentenceNodeList = null;
            }
            //Put the list back in the map                  
            namesSentencesMap.put(fromName, sentenceList);
        }
    }

    public static void main(String[] args) {
        XMLReader reader = new XMLReader();
        reader.buildNamesSentencesMap(reader.getDocument("<your_xml_file>"));

        for(String names: reader.namesSentencesMap.keySet()){
            System.out.println("Name: "+names+"\tTotal Sentences: "+reader.namesSentencesMap.get(names).size());
        }
    }
}

注意:这只是一个演示,你需要修改它以满足你的需要。我已经根据你的XML创建了它,以显示一种方法。