我试图了解如何识别特定的 XML 并在其中一个标签中提取特定的数据。
当我尝试实现上述目标时,我一直在浏览文档和示例,然后进行分支和修改。
我正在使用StAX
我的整个代码和 xml 文件位于本文的底部。
我有两个问题: 1)我有一个问题,为什么我的部分代码没有按照我想象的方式运行。 我有
String elem = se.getName().toString();
System.out.printf("elem = %s\n",elem);
if( se.getName().toString() == "{http://www.publishing.org}Date")
//if( elem == "1")
{
System.out.println("Here !!!!!!!!!!!!!!!!!");
}
我的 System.out.printf(“elem = %s\n”,elem);
产量:elem = { http://www.publishing.org }日期
但是我的 if 语句 if( se.getName().toString() == "{ http://www.publishing.org }Date") 从来都不是真的,这意味着我永远不会得到“这里!!!”
问题2, 为什么我会得到:
{http://www.publishing.org}author
{http://www.publishing.org}Date
{http://www.publishing.org}ISBN
不仅仅是作者、日期和 ISBN?为什么每一行也给我 { http://publishing.org }?
public static void main(String[] args) throws FileNotFoundException, XMLStreamException
{
// TODO code application logic here
//System.out.println("Here");
//String filename = null;
String filename = "BookCatalog.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();
if( se.getName().toString() == "{http://www.publishing.org}Date")
//if( elem == "1")
{
System.out.println("Here !!!!!!!!!!!!!!!!!");
}
Iterator attributes = se.getNamespaces();
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
/*case XMLEvent.END_ELEMENT>
EndElement ee = event.asEndElement();
System.out.print("</"+ee.getName()+">");
break;
* */
}// end witch
}// end while
reader.close();
}//end Main
和 XML: http://www.publishing.org"> Yaga 体式 迪伦达 1966年 81-40 迪伦达 11.50 Yaga 体式 J.K. 1954年 0-06 哈珀 2.95
最佳答案
问题 1:这看起来像 .equals() 与 ==。我认为你想要 .equals()。
关于java - StAX JAVA 提取特定标签和数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15138360/