根据Stackoverflow上某人的建议,我将解析方法更改为SAXParser。
多亏了不同的教程,我才能够使它正常工作,而且不得不说它的运行速度更快(这对于我的应用程序非常重要)。
但是,问题是我的XML文件比我所见的教程示例XML更深入。
这是我的XML文件的示例:
<Message>
<Service>servicename</Service>
<Insurances>
<BreakdownInsurance>
<Name>Insurance name</Name>
<InsuranceNR/>
<LicenseNr/>
</BreakdownInsurance>
<CarDamageInsurance>
<Name>Insurance name 2</Name>
<InsuranceNR></InsuranceNR>
</CarDamageInsurance>
</Insurances>
<Personal>
<Name>my name</Name>
</Personal>
</Message>
我可以获得姓名等个人详细信息,但是我的代码似乎不适用于保险。我认为这是因为它是一个节点。
这是我在Handler类中使用的代码:
@Override
public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException {
currentElement = true;
if (localName.equals("Message")) {
geg = new GegevensXML();
}
}
@Override
public void endElement(String namespaceURI, String localName, String qName) throws SAXException {
currentElement = false;
/********** Autopech **********/
if (localName.equals("Name")) {
geg.setAutopechMaatschappij(currentValue);
}
else if (localName.equals("InsuranceNR")){
geg.setAutopechPolis(currentValue);
}
else if (localName.equals("LicenseNr")){
geg.setAutopechKenteken(currentValue);
}
@Override
public void characters(char ch[], int start, int length) {
if (currentElement) {
currentValue = new String(ch, start, length);
currentElement = false;
}
那么我该如何调整呢?
最佳答案
@Override
public void startElement(String namespaceURI,String localName,String qName,Attributes atts)抛出SAXException {
currentElement = true;
如果(localName.equals(“ Message”)){
geg = new GegevensXML();
}
if(localName.equals(“ BreakdownInsurance”))
{
BreakdownInsurance = true;
}
}
@Override
public void endElement(String namespaceURI,String localName,String qName)抛出SAXException {
currentElement = false;
/ ********** Autopech ********** /
如果(localName.equals(“ Name”))
{
如果(BreakdownInsurance)
{
geg.setBreakdownInsuranceName(currentValue);
BreakdownInsurance = false;
}
其他
{
geg.setAutopechMaatschappij(currentValue);
}
}
否则,如果(localName.equals(“ InsuranceNR”)){
geg.setAutopechPolis(currentValue);
}
否则,如果(localName.equals(“ LicenseNr”)){
geg.setAutopechKenteken(currentValue);
}
同样,在其他情况下也可以这样做...'BreakdownInsurance'是一个布尔值。将其用作标志...