【发布时间】:2015-04-10 19:38:49
【问题描述】:
在下面的代码中,我试图读取父类别、属于它们的类别以及它们是否包含子类别。
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,但它随后将它们打印在列出的每个类别上,即使它们不包含子类别。
任何帮助将不胜感激。干杯
【问题讨论】:
-
没关系,解决了这个问题。
-
这听起来可能很傻,但在这种情况下,您可以发布您对自己问题的回答,并接受它,以便关闭此问题。谢谢!