2016-10-04 88 views
0

我有一個XML文件是這樣的:如何替換xml文件中的一部分字符串?

<Verbiage> 
     The whiskers plots are based on the responses of incarcerated 
     <Choice> 
      <Juvenile> juveniles who have committed sexual offenses. </Juvenile> 
      <Adult> adult sexual offenders. </Adult> 
     </Choice> 
     If the respondent is a 
     <Choice> 
      <Adult>convicted sexual offender, </Adult> 
      <Juvenile>juvenile who has sexually offended, </Juvenile> 
     </Choice> 
     #his/her_lc# percentile score, which defines #his/her_lc# position 
     relative to other such offenders, should be taken into account as well as #his/her_lc# T score. Percentile 
     scores in the top decile (> 90 %ile) of such offenders suggest that the respondent 
     may be defensive and #his/her_lc# report should be interpreted with this in mind. 
    </Verbiage> 

我試圖找到一種方法來解析XML文件(我一直在使用DOM),搜索#他/ her_lc#和替換與「她」。我試過使用FileReader,BufferedReader,string.replaceAll,FileWriter,但那些都不起作用。

有沒有一種方法可以使用XPath執行此操作?

最終,我想爲這個字符串搜索這個xml文件,並用另一個字符串替換它。

我必須在字符串周圍添加一個標籤我希望它解析它嗎?

代碼我想:

protected void parse() throws ElementNotValidException { 
    try { 
     //Parse xml File 
     File inputXML = new File("template.xml"); 
     DocumentBuilderFactory parser = DocumentBuilderFactory.newInstance(); // new instance of doc builder 
     DocumentBuilder dParser = parser.newDocumentBuilder(); // calls it 
     Document doc = dParser.parse(inputXML); // parses file 

     FileReader reader = new FileReader(inputXML); 
     String search = "#his/her_lc#"; 
     String newString; 

     BufferedReader br = new BufferedReader(reader); 
     while ((newString = br.readLine()) != null){ 
      newString.replaceAll(search, "her"); 
     } 

     FileWriter writer = new FileWriter(inputXML); 
     writer.write(newString); 
     writer.close(); 

    } catch (ParserConfigurationException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } catch (SAXException e) { 
     e.printStackTrace(); 
    } 

代碼我得到了解決:

try { 
     File inputXML = new File("template.xml"); // creates new input file 
     DocumentBuilderFactory parser = DocumentBuilderFactory.newInstance(); // new instance of doc builder 
     DocumentBuilder dParser = parser.newDocumentBuilder(); // calls it 
     Document doc = dParser.parse(inputXML); // parses file 
     doc.getDocumentElement().normalize(); 

     NodeList pList = doc.getElementsByTagName("Verbiage"); // gets element by tag name and places into list to begin parsing 

     int gender = 1; // gender has to be taken from the response file, it is hard coded for testing purposes 
     System.out.println("----------------------------"); // new line 

     // loops through the list of Verbiage tags 
     for (int temp = 0; temp < pList.getLength(); temp++) { 
      Node pNode = pList.item(0); // sets node to temp 

      if (pNode.getNodeType() == Node.ELEMENT_NODE) { // if the node type = the element node 
       Element eElement = (Element) pNode; 
       NodeList pronounList = doc.getElementsByTagName("pronoun"); // gets a list of pronoun element tags 

       if (gender == 0) { // if the gender is male 

        int count1 = 0; 
        while (count1 < pronounList.getLength()) { 

         if ("#he/she_lc#".equals(pronounList.item(count1).getTextContent())) { 
          pronounList.item(count1).setTextContent("he"); 
         } 

         if ("#he/she_caps#".equals(pronounList.item(count1).getTextContent())) { 
          pronounList.item(count1).setTextContent("He"); 
         } 

         if ("#his/her_lc#".equals(pronounList.item(count1).getTextContent())) { 
          pronounList.item(count1).setTextContent("his"); 
         } 
         if ("#his/her_caps#".equals(pronounList.item(count1).getTextContent())) { 
          pronounList.item(count1).setTextContent("His"); 
         } 

         if ("#him/her_lc#".equals(pronounList.item(count1).getTextContent())) { 
          pronounList.item(count1).setTextContent("him"); 
         } 
         count1++; 
        } 
        pNode.getNextSibling(); 

       } else if (gender == 1) { // female 
        int count = 0; 
        while (count < pronounList.getLength()) { 

         if ("#he/she_lc#".equals(pronounList.item(count).getTextContent())) { 
          pronounList.item(count).setTextContent("she"); 
         } 

         if ("#he/she_caps3".equals(pronounList.item(count).getTextContent())) { 
          pronounList.item(count).setTextContent("She"); 
         } 

         if ("#his/her_lc#".equals(pronounList.item(count).getTextContent())) { 
          pronounList.item(count).setTextContent("her"); 
         } 
         if ("#his/her_caps#".equals(pronounList.item(count).getTextContent())) { 
          pronounList.item(count).setTextContent("Her"); 
         } 

         if ("#him/her_lc#".equals(pronounList.item(count).getTextContent())) { 
          pronounList.item(count).setTextContent("her"); 
         } 
         count++; 
        } 
        pNode.getNextSibling(); 
       } 
      } 
     } 
     // write the content to file 
     TransformerFactory transformerFactory = TransformerFactory.newInstance(); 
     Transformer transformer = transformerFactory.newTransformer(); 
     DOMSource source = new DOMSource(doc); 

     System.out.println("-----------Modified File-----------"); 
     StreamResult consoleResult = new StreamResult(System.out); 
     transformer.transform(source, new StreamResult(new FileOutputStream("template.xml"))); // writes changes to file 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 

}

這段代碼我想,如果我能想出如何將標籤關聯會工作用代詞Parser代詞這個代碼是在

+0

它說它那裏..我已經嘗試filereader和文件編寫器使用string.replace所有。我不知道如何搜索正則表達式或如何使用分詞器,如果這將有助於這裏。我可以使用dom解析文件,但是我所尋找的單詞沒有標籤,所以我可以找出如何通過標籤添加新的標籤和搜索元素,或者如果有人知道另一種搜索字符串的方法有幫助 – Felicia

+1

你的意思是'那些沒有工作'?它引發了一個例外?它有意想不到的結果?請粘貼一段代碼/堆棧跟蹤,以便人們可以幫助您 – eltabo

+0

FileReader/Writer只是沒有做任何事情。它跑了,但它並沒有改變我搜索的字符串。不知道爲什麼。 – Felicia

回答

1

我用這個例子和你的templ ate.xml,我認爲它的工作原理。

public static void main(String[] args) { 

     File inputXML = new File("template.xml"); 
     BufferedReader br = null; 
     String newString = ""; 
     StringBuilder strTotale = new StringBuilder(); 
     try { 

     FileReader reader = new FileReader(inputXML); 
     String search = "#his/her_lc#"; 


     br = new BufferedReader(reader); 
     while ((newString = br.readLine()) != null){ 
      newString = newString.replaceAll(search, "her"); 
      strTotale.append(newString); 
     } 

     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } // calls it 
     finally 
     { 
      try { 
       br.close(); 
      } catch (IOException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
     } 


     System.out.println(strTotale.toString()); 


    } 

首先,你必須重新分配的replaceAll的結果:

newString = newString.replaceAll(search, "her"); 

其次,我用一個StringBuffer來收集所有的行。

我希望這個幫助。

相關問題