0
在下面的代码中,我试图读出父类别,属于它们的类别以及它们是否包含子类别。打印出Xpath节点
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,但是它会在列出的每个类别上打印出来,即使它们不包含子类别。
任何帮助将不胜感激。干杯
从不介意,解决了这个问题。 – vessel 2015-03-31 08:24:50
这可能听起来很愚蠢,但我这种情况下,你可以发布你的答案给你自己的问题,并接受它,以便这个问题可以关闭。谢谢! – potame 2015-04-02 16:00:29