Search code examples
javaxmlparsingjavafxobservablelist

XML node list as JavaFX observable list?


got a problem...

I have some XML file with root element, 3 element with same name and different attribute and also each element has got some elements.

I want to have element attributes called "id" in FX observable list. No idea what to do.


Solution

  • Since you didn´t give me much information, I have to explain it with some dummy-code.
    So let´s say you have this XML:

    <root id="0">
        <sub1 id="1">
            <hell1>hell1</hell1>
        </sub1>
        <sub2>
            <hell2 id="2">hell2</hell2>
        </sub2>
        <sub3>sub3</sub3>
    </root>
    

    Please note, that the "id"-attributes are in different element levels, as you said.

    From here I would also advise you to use xpath like Heri. The simplest xpath to get all elements with "id"-attributes from XML is:

    //*[@id]
    

    If you don´t know how to work with XML and Xpath in Java you can look it up here:
    How to read XML using XPath in Java
    Which is the best library for XML parsing in java

    If i wanted to get all "id"-attribute values from my XML it would look like this:

    // My Test-XML
    final String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
            "<root id=\"0\">\n" +
            "\t<sub1 id=\"1\">\n" +
            "\t\t<hell1>hell1</hell1>\n" +
            "\t</sub1>\n" +
            "\t<sub2>\n" +
            "\t\t<hell2 id=\"2\">hell2</hell2>\n" +
            "\t</sub2>\n" +
            "\t<sub3>sub3</sub3>\n" +
            "</root>";
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    // Here you have to put your XML-Source (String, InputStream, File)
            Document doc = builder.parse(new InputSource(new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8))));
    XPathFactory xPathFactory = XPathFactory.newInstance();
    XPath xpath = xPathFactory.newXPath();
    // The xpath from above
    XPathExpression expr = xpath.compile("//*[@id]");
    // Here you get the node-list of all elements with an attribute named "id"
    NodeList nodeList = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
    for (int i = 0; i < nodeList.getLength(); i++) {
        // run through all nodes
        Node node = nodeList.item(i);
        // fetch the values from the "id"-attribute
        final String idValue = node.getAttributes().getNamedItem("id").getNodeValue();
        // Do something awesome!!! 
        System.out.println(idValue);
    }
    

    I assume that you know how to put the values into your observable list then. :)
    If you have any more questions, feel free to ask.

    PS: If you show me your XML, I can help you in a more efficient way.