简体   繁体   中英

Search a particular string in XML file using Stax

I'm trying to check whether particular 2 strings are present in an XML file or not.

The xml code

<datapoint nature="PARAMETRIC" division="COLL_COMP_ENG" programmaticName="t_val_calc_enrg_accumulated" />
<datapoint nature="PARAMETRIC" division="COLL_COMP_ENG" programmaticName="t_val_calc_pwr_consumed" />

Java code..

    Integer count=0;
    XMLInputFactory f = XMLInputFactory.newInstance();
     XMLStreamReader rdr = f.createXMLStreamReader(new FileReader("E:\\SVN\\MasterData\\MasterData.xml"));

      while (rdr.hasNext()) {
      if (rdr.next() == XMLStreamConstants.START_ELEMENT) {
      if (rdr.getLocalName().equals("datapoint")) {
           String txt = rdr.getAttributeValue("programmaticName");
            if (txt.indexOf("t_val_calc_pwr_consumed") > 0 || txt.indexOf("t_val_calc_enrg_accumulated") > 0) {
              System.out.println(txt);
              count++;
            }
       }
  }
  }
System.out.println(count);

Whenever i try to run the code i get an error message "String cannot be converted to int" for the line.

  String txt = rdr.getAttributeValue("programmaticName");  

The stacktrace is

     Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - Erroneous sym type: javax.xml.stream.XMLStreamReader.getAttributeValue
at sample.eXTRACT.main(eXTRACT.java:42)
     Java Result: 1
     BUILD SUCCESSFUL (total time: 2 seconds)

The expected output:

   t_val_calc_enrg_accumulated
   t_val_calc_pwr_consumed

XMLStreamReader#getAttributeValue takes an int as the index of the attribute as an argument (eg in this case, rdr.getAttributeValue(2) ).

You are parametrizing it with a single String , which will not compile.

Alternatively to an int -based attribute order indexing, you can use the overload: getAttributeValue(String namespaceURI, String localName)

API here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM