2014-02-18 27 views
-1

我想問問,如果有可能,我算例如特殊的字母或數字:從.xml文件的Java:計數從.XML一個特殊的字母或數字

「A」 ? 並把它寫成一個變量?

例如:

foo.xml:

<questions> 
<question> 
<variante> A: variante1 </variante> 
<variante> B: variante2 </variante> 
</question> 
<question> 
<variante> A: variante1 </variante> 
<variante> B: variante2 </variante> 
</question> 
<question> 
<variante> A: variante1 </variante> 
<variante> B: variante2 </variante> 
</question> 
</questions> 

INT計數器= 3

因爲我有三個 「A:」

我要使用的變量爲解決方案一句話:

syso(「你有+ + fromPoint +」from + counter +「Points」);

感謝您的幫助!

+1

是的,這是可能的。還有其他問題嗎? – Pshemo

+0

當然,用字符串讀入XML,每次找到該字母時都要搜索該字母並增加一個計數器。 – Smutje

+0

你是什麼意思_「把它寫成變量」_?另外,顯示你到目前爲止所嘗試的內容 – Baby

回答

1
StringBuilder sb = new StringBuilder(); 
    BufferedReader br = new BufferedReader(new FileReader(PATH_TO_XML_FILE)); 
    String sCurrentLine = null; 

    while ((sCurrentLine = br.readLine()) != null) { 
     sb.append(sCurrentLine); 
    } 

    Pattern pattern = Pattern.compile("A:"); 
    Matcher matcher = pattern.matcher(sb); 
    int count = 0; 
    while (matcher.find()){ 
     count++; 
    } 

    System.out.println(count); 

這個答案包含的代碼在XML文件作爲一個字符串也讀,matcher.find()只查找匹配的下一個實例,所以你必須惱人地循環整個事情。

0

你可以做以下的事情

1) Read the XML File using say filereader class. 
2) Read the content of the file as string 
3) For getting the number of instance of a particular content, you can either your 
    String class equals method and increment a counter on every match found or use 
    regex (Pattern and Matcher class) to know how many times, the content occured 
0

如果你想使用DOM,你可以做這樣的事情:

public class blah { 
      public static void main(String[] args) { 
       File docFile = new File("foo.xml"); 
       Document doc = null; 

       try { 
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
        DocumentBuilder db = dbf.newDocumentBuilder(); 
        doc = db.parse(docFile); 
       } 
       catch (Exception e) { 
        System.out.println("problem parsing the file"); 
        System.exit(1); 
       } 
       Element root = doc.getDocumentElement(); 
       NodeList list = root.getElementsByTagName("variante"); 
       for (int i = 0; i < list.getLength(); i++) { 
        String blah = list.item(i).getTextContent(); 
        if (blah.charAt(0) == 'A') { 
          System.out.println("You have " + reachedPoints + "from " + counter + "Points"); 
        } 
      } 
    } 
    } 

最重要的部分是在for循環。它存儲「variante」標籤的文本內容,然後檢查文本內容的第一個字母是否爲「A」。如果它是「A」,那麼我打印出您在問題中發佈的字符串。

相關問題