java 如何使用 XMLReader 解析 xml 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4734365/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 07:47:06  来源:igfitidea点击:

How to parse xml file using XMLReader

javaandroid

提问by Aditya Mehta

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

我有一个“contacts.xml”文件,它的结构是:

<?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>

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?

我不想要 xml 的“ContactId”和“TokenId”元素的值。我应该如何编码?

回答by Aditya Mehta

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

回答by chikka.anddev

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

你可以在这里得到很多信息:http: //www.ibm.com/developerworks/opensource/library/x-android/