开发者

How to parse xml file using XMLReader

开发者 https://www.devze.com 2023-02-05 17:15 出处:网络
I have a \"contacts.xml\" file, its structure is: <?xml version=\"1.0\" encoding=\"UTF-8\"?> <Contacts>

I have a "contacts.xml" file, its structure is:

<?xml version="1.0" encoding="UTF-8"?>
<Contacts>
   <Contact>
      <ContactId>1</ContactId> 
      <ContactName>Aditya  Kothari</ContactName>
      <MobilePhone1>NA</MobilePhone1> 
      <MobilePhone2>NA</MobilePhone2> 
      <OfficePhone1&g开发者_StackOverflow社区t;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>

Now i am doing this-

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

I do not want values of "ContactId" and "TokenId" elements of xml. How should i code?


Recently i got this 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();
}


You can get lots of information fem here:http://www.ibm.com/developerworks/opensource/library/x-android/

0

精彩评论

暂无评论...
验证码 换一张
取 消