我得到了我需要的确切输出,但我必须为我的程序使用 POJO 类,我搜索了很多问题,但我没有明确的想法。帮助我解决这个问题,提前感谢我在 java 中对 xml phrse 的编码下面给出。
ReadAndPrintXMLFile:: 的编码
import org.w3c.dom.*;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import java.net.URL;
import java.io.InputStream;
public class ReadAndPrintXMLFile{
public static void main (String argv []){
try {
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
URL url = new URL("http://xxxxxxxxxxxxxxxx");
InputStream stream = url.openStream();
Document doc = docBuilder.parse(stream);
// normalize text representation
doc.getDocumentElement ().normalize ();
System.out.println ("Root element of the doc is " +
doc.getDocumentElement().getNodeName());
NodeList listOfPersons = doc.getElementsByTagName("head");
int totalPersons = listOfPersons.getLength();
System.out.println("Total no of head : " + totalPersons);
for(int s=0; s<listOfPersons.getLength() ; s++){
Node firstPersonNode = listOfPersons.item(s);
if(firstPersonNode.getNodeType() == Node.ELEMENT_NODE){
Element firstPersonElement = (Element)firstPersonNode;
//-------
NodeList firstNameList = firstPersonElement.getElementsByTagName("heading");
Element firstNameElement = (Element)firstNameList.item(0);
NodeList textFNList = firstNameElement.getChildNodes();
System.out.println("Heading : " +
((Node)textFNList.item(0)).getNodeValue().trim());
}//end of if clause
}//end of for loop with s var
}catch (SAXParseException err) {
System.out.println ("** Parsing error" + ", line "
+ err.getLineNumber () + ", uri " + err.getSystemId ());
System.out.println(" " + err.getMessage ());
}catch (SAXException e) {
Exception x = e.getException ();
((x == null) ? e : x).printStackTrace ();
}catch (Throwable t) {
t.printStackTrace ();
}
//System.exit (0);
}//end of main
}
对于这个 xml 解析程序,我必须使用 POJO 类。所以为此我创建了一个这样的类
public class POJOurl {
private String heading;
public String getHeading() {
return heading;
}
public void setHeading(String heading) {
this.heading = heading;
}
}
在这里,我不知道如何在我的程序中使用这些 get 和 set 方法,使用这些 public String getHeading() 和 public void setHeading(String heading) 我必须执行程序..我必须得到我得到的输出现在..唯一的事情是我必须为这个程序使用 POJO 类
输出::
Root element of the doc is root1
Total no of head : 4
Heading : Appliance Repairs
Heading : Air conditioning and refrigeration services
Heading : Accountants
Heading : Accident Management