【问题标题】:Print out of Xpath nodes打印出 Xpath 节点
【发布时间】: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,但它随后将它们打印在列出的每个类别上,即使它们不包含子类别。

任何帮助将不胜感激。干杯

【问题讨论】:

  • 没关系,解决了这个问题。
  • 这听起来可能很傻,但在这种情况下,您可以发布您对自己问题的回答,并接受它,以便关闭此问题。谢谢!

标签: java xpath


【解决方案1】:

抱歉,我没有意识到我必须接受答案才能关闭问题.. 这是一个没有正确读取 xml 的情况。每个父类别都有一个由其子类别引用的 ID。所以我只是检查了包含 pid(parentID) 的 ID 值的类别,并将它们与他们的父母一起打印出来..

【讨论】:

    猜你喜欢
    • 2015-12-30
    • 1970-01-01
    • 1970-01-01
    • 2014-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多