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