繁体   English   中英

使用Stax搜索XML文件中的特定字符串

[英]Search a particular string in XML file using Stax

我正在尝试检查XML文件中是否存在特定的2个字符串。

xml代码

<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代码

    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);

每当我尝试运行代码时,我都会收到一条错误消息“无法将字符串转换为int”。

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

stacktrace是

     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)

预期输出:

   t_val_calc_enrg_accumulated
   t_val_calc_pwr_consumed

XMLStreamReader#getAttributeValueint作为属性的索引作为参数(例如,在本例中为rdr.getAttributeValue(2) )。

您正在使用单个String对其进行参数化,该String无法编译。

除了基于int的属性顺序索引以外,还可以使用重载: getAttributeValue(String namespaceURI, String localName)

API 在这里

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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