使用SAX和Java比较两个属性值

时间:2015-04-30 11:38:13

标签: java parsing sax

这是我的security.xml

我想测试temperaturet具有相同的标签presencep具有相同的标签使用SAX和java。

有人能帮助我!!?

 <root>

   <component classname="temp.impl.Temperatureservice" name="TemperatureSecurity">
<attributes>
       <attribute>

     <name> temperature</name>

        <label>L</label>

     </attribute>
 </attributes>
     </component> 


  <component classname="pres.impl.Presenceservice" name="PresenceSecurity">
<attributes>
    <attribute> 

<name>presence</name>

      <label>H</label>

   </attribute>
   </attributes>
 </component>

 <component classname="anal.AnalyserService" name="ManagerSecurity">
 <attributes>
       <attribute >

      <name>t</name>

        <label>L</label>

      </attribute>

<attribute>

 <name>p</name>

     <label>H</label>

        </attribute>
</attributes>
   </component>  


</root>
我尝试了什么:

  public class MyHandler extends DefaultHandler {

private List<Component> compList = null;
private Component comp = null;
boolean bnameatt = true;
boolean bName = true;
boolean blabel = false;
String label;
private String temp;
private String lab;

@Override
public void startElement(String uri, String localName, String qName, Attributes attributes)
        throws SAXException {

    if (qName.equalsIgnoreCase("component")) {

        String name = attributes.getValue("name");

        comp = new Component();
        comp.setName(name);
        //initialize list
        if (compList == null) {
            compList = new ArrayList<>();
        }
    } else if (qName.equalsIgnoreCase("name")) {
        temp = attributes.getValue("name");
        bnameatt = true;
    } else if (qName.equalsIgnoreCase("label")) {
        lab = attributes.getValue("label");
        blabel = true;

    }
}

@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
    System.out.println("temp " + temp + " lab " + lab);
    if (temp.equalsIgnoreCase("temperature")) {

        label = lab;
    } else if (temp.equalsIgnoreCase("t")) {
        System.out.println("temp " + temp + " lab " + lab);
        if (lab.equals(label)) {
            System.out.println("okk");
        } else {
            System.out.println("not ok");
        }
    }
    blabel=false;
    bnameatt=false;
}

}

我在saax.MyHandler.endElement上有一个NullPointerException(MyHandler.java:56)if(temp.equalsIgnoreCase("temperature")

1 个答案:

答案 0 :(得分:1)

您需要使用endElement回调来保存使用builder和builder1构建的内容,然后将其与之前的结果进行比较。类似的东西:

  public void endElement(String uri, String localName, String qName) {
       if (builder.toString().equals("temperature")) 
           temprature_label = builder1.toString();
       else if (builder.toString().equals("t")) {
            if (builder1.toString().equals(temprature_label)) 
                System.out.println("okkk");
            else
                System.out.println("not ok");
       }
    }