2011-01-19 65 views
1

我有一個「contacts.xml」文件解析XML文件,其結構爲:如何使用的XMLReader

<?xml version="1.0" encoding="UTF-8"?> 
<Contacts> 
    <Contact> 
     <ContactId>1</ContactId> 
     <ContactName>Aditya Kothari</ContactName> 
     <MobilePhone1>NA</MobilePhone1> 
     <MobilePhone2>NA</MobilePhone2> 
     <OfficePhone1>NA</OfficePhone1> 
     <OfficePhone2>NA</OfficePhone2> 
     <OfficePhone3>NA</OfficePhone3> 
     <HomePhone1>999-367-3944</HomePhone1> 
     <HomePhone2>NA</HomePhone2> 
     <TokenId>mtn</TokenId> 
    </Contact> 
    <Contact> 
     <ContactId>2</ContactId> 
     <ContactName>Jai Mandloi </ContactName> 
     <MobilePhone1>NA</MobilePhone1> 
     <MobilePhone2>NA</MobilePhone2> 
     <OfficePhone1>NA</OfficePhone1> 
     <OfficePhone2>NA</OfficePhone2> 
     <OfficePhone3>NA</OfficePhone3> 
     <HomePhone1>800-742-9678</HomePhone1> 
     <HomePhone2>NA</HomePhone2> 
     <TokenId>mtn</TokenId> 
    </Contact> 
</Contacts> 

我現在做這個 -

File xmlFile = new File("E:\\contacts.xml"); 
InputStream is = new FileInputStream(xmlFile); 
XMLInputFactory factory = XMLInputFactory.newInstance(); 
XMLStreamReader reader = factory.createXMLStreamReader(is); 
while(reader.hasNext()) 
{ 
    if(reader.hasText() 
    { 
     System.out.println(reader.getText()); 
    } 
    reader.next(); 
} 

我不希望的值xml的「ContactId」和「TokenId」元素。 我應該如何編碼?

回答

2

最近我得到這個way-

while(reader.hasNext()) 
{ 
    if(reader.getEventType()==XMLStreamConstants.START_ELEMENT) 
    { 
    if(!reader.getLocalName().equals("ContactId") && !reader.getLocalName().equals("TokenId") && !reader.getLocalName().equals("Contacts") && !reader.getLocalName().equals("Contact")) 
    { 
     System.out.println(reader.getElementText()); 
    }   
    } 
    reader.next(); 
}