1

我目前正在从事一个学术项目,在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”或其他评论者的句子,即使是所有使用的通用形式,XPath但都失败了。我对这些技术很陌生,包括 JAVA 和任何不知道如何实现它的人。SAXDOM

任何人都可以具体指导我如何使用上述任何技术获得它,或者是否有其他更好的策略来做到这一点?

(注:稍后我想把它放在hashmap评论者(justin dolske)的位置和值是(所有句子)之类的HashMap (key, value)地方)key = name

紧急帮助将不胜感激。

4

2 回答 2

1

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

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

将每个 'Turn' 放入 aMap< String, List< Turn >>中,使用Turn.Fromas 键。

完成后,您可以编写:

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

于 2012-10-28T09:21:34.753 回答
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 创建了它,以展示一种方法。

于 2012-10-28T09:47:43.677 回答