在下面的代码中,我试图读取父类别、属于它们的类别以及它们是否包含子类别。
public static void getcategories() throws Exception
{
XPathContext xpath = new XPathContext(new FileReader("//categorylistEN.xml"));
NodeList categories = xpath.getXPathNodes("//CategoriesList/Category");
NodeList scategories = xpath.getXPathNodes("//CategoriesList/Category/SubCategories/SubCategory");
NodeList pcategories = xpath.getXPathNodes("//CategoriesList/Category/ParentCategory");
for(int i = 0; i < pcategories.getLength(); i++)try
{
HashMap<String, String> pcats = new HashMap();
Node n = pcategories.item(i);
String pid = " ("+n.getAttributes().getNamedItem("ID").getNodeValue()+")";
String pname = n.getFirstChild().getNextSibling().getTextContent().replaceAll("n", "").trim() +" ";
pcats.put(pname,pid);
System.out.println(pcats);
Node cats = categories.item(i);
String catid = cats.getAttributes().getNamedItem("ID").getNodeValue();
NodeList catn = cats.getChildNodes();
Node name = catn.item(5);
String catname = name.getAttributes().getNamedItem("Value").getNodeValue();
System.out.println(pcats +" - "+ catname + " = (" +catid+")");
Node scat = scategories.item(i);
String sid = scat.getAttributes().getNamedItem("ID").getNodeValue();
System.out.println(pcats +" - "+ catname + " = (" +catid+")" + " = (" +sid+")");
}
catch (Exception e)
{
System.out.println("NoID" );
}
}
它应该以以下格式读出:
ParentCategory =(ID)
ParentCategory =(ID) Category =(ID)
ParentCategory =(ID)
ParentCategory =(ID) Category =(ID)
ParentCategory =(ID) Category =(ID) SubCategory =(ID)
ParentCategory =(ID)
ParentCategory =(ID) Category =(ID)
ParentCategory =(ID)
ParentCategory =(ID) Category =(ID)
父类别和类别可以正常工作,但并非所有类别都包含子类别。如何检查子类别并将其打印在包含该子类别的类别旁边??我尝试了一些循环,成功地在文件中获得了子类别ID,但它会将它们打印在列出的每个类别上,即使它们不包含子类别。
如有任何帮助,我们将不胜感激。干杯
对不起,我没有意识到我必须接受答案才能解决问题。。这是一个没有正确读取xml的情况。每个父类别都有一个由其子类别引用的ID。所以我只是检查了包含ID值pid(parentID)的类别,并将它们与它们的父母一起打印出来。。