在 StAX 解析示例中,我正在设置一个String dataread = se.getElementText();
. 我立即成功打印了该字符串(数据读取)。
但是,在我的代码中的其他任何地方,它都不起作用,它报告它找不到符号dataread
。您将看到它正在尝试 5 个其他点进入代码 - 所有报告都相同。if 语句中的第一行有效。
如何在程序的其他地方使用字符串“dataread”?
谢谢
public static void main(String[] args) throws FileNotFoundException, XMLStreamException
{
// TODO code application logic here
//System.out.println("Here");
//String filename = null;
String filename = "BookCatalog2.xml";
XMLInputFactory factory = XMLInputFactory.newInstance();
XMLEventReader reader = factory.createXMLEventReader(new FileReader(filename));
while(reader.hasNext())
{
XMLEvent event = reader.nextEvent();
XMLEvent nextEvent = reader.peek();
switch (event.getEventType())
{
case XMLEvent.START_ELEMENT:
StartElement se = event.asStartElement();
//System.out.println("Here");
//System.out.print("<" + se.getName());
//System.out.print(" " + se.getName());
//System.out.printf("\n");
String elem = se.getName().toString();
//String elem = "1";
//System.out.printf("elem = %s\n",elem);
//String ele = event.getAttributeName();
System.out.printf("event = %s\n",se.getName());
//if( se.getName().toString() == "{http://www.publishing.org}Date")
if( se.getName().toString().equals("Date"))
//if( elem == "1")
{
System.out.println("Here !!!!!!!!!!!!!!!!!");
String dataread = reader.getElementText();
//System.out.printf("data = %s\n",reader.getElementText());
System.out.printf("data = %s\n",dataread);
}
Iterator attributes = se.getNamespaces();
System.out.printf("DATA READ = %s\n",dataread);
while(attributes.hasNext())
{
Attribute attr= (Attribute)attributes.next();
System.out.print(" " + attr.getName() + "=\"" +attr.getValue() +"\"");
System.out.printf("\n");
}//end while loop
System.out.print(">");
if(nextEvent.isCharacters())
{
Characters c = reader.nextEvent().asCharacters();
if(!c.isWhiteSpace())
System.out.print(c.getData());
System.out.printf("\n");
}// end if
System.out.printf("DATA READ = %s\n",dataread);
/*case XMLEvent.END_ELEMENT>
EndElement ee = event.asEndElement();
System.out.print("</"+ee.getName()+">");
break;
* */
System.out.printf("DATA READ = %s\n",dataread);
}// end witch
System.out.printf("DATA READ = %s\n",dataread);
}// end while
System.out.printf("DATA READ = %s\n",dataread);
reader.close();
}//end Main
}// public claSS