Home > front end >  How to treat rdf xml resources with java dom
How to treat rdf xml resources with java dom

Time:12-08

Here is my xml document :

<rdf:RDF 
xmlns:test="http://www.test/2022#" 
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" 
xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#" 
xml:base="http://www.desktop-eqkvgq5.net/2022#">
<test:Dog rdf:ID="_100">
<test:Animal.Name>Jeck</test:Animal.Name>
<test:Dog.breed>Akita</test:Dog.breed>
<test:Animal.age rdf:resource="#_1000"/>
<test:Animal.legs rdf:resource="#_1100"/>
</test:Dog>
<test:Cat rdf:ID="_101">
<test:Animal.Name>Tom</test:Animal.Name>
<test:Cat.breed>Munchkin</test:Cat.breed>
<test:Animal.age rdf:resource="#_1001"/>
<test:Animal.legs rdf:resource="#_1100"/>
</test:Cat>
</rdf:RDF>

I'm using java dom to parse. Paring ID and name is clear but How should rdf:resource="#_1000"/>?

Here is my code :

        try {
        DocumentBuilderFactory factory_parsing = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder_parsing = factory_parsing.newDocumentBuilder();
        Document document = builder_parsing.parse("D://Test/dog_test.xml");
        document.getDocumentElement().normalize();

        System.out.println("Root element: "   document.getDocumentElement().getNodeName()); //
        NodeList nList = document.getElementsByTagName("test:Dog");
        System.out.println(nList.getLength());


        for(i=0; i<nList.getLength();i  )
        {
            Node nNode = nList.item(i);

            System.out.println("\nCurrent Element: "   nNode.getNodeName());

            if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                Element elem = (Element) nNode;

                String id = elem.getAttribute("rdf:ID");
                String name = elem.getElementsByTagName(("test:Animal.Name")).item(0).getTextContent();
                String age = elem.getAttribute("rdf:resource");


                System.out.printf("id : %s%n", id);
                System.out.printf("Name : %s%n", name);
                System.out.printf("age : %s%n", age);
            }
        }
    } catch (Exception e){
        e.printStackTrace();
    }

The result : Current Element: test:Dog//id : _100//Name : Jeck//age ://It return age is blank


[Additional] I solved it on this site. https://mkyong.com/java/how-to-read-xml-file-in-java-dom-parser/ Thank you for your reply.

CodePudding user response:

To parse the <test:Animal.age rdf:resource="#_1000"/> element, you can use the getAttribute() method of the Element class. This will return the value of the attribute you specify, in this case the rdf:resource value.

For example:

String resourceValue = elem.getAttribute("rdf:resource");

This will return the value of the rdf:resource attribute, i.e. "#_1000". You can then use this value to access the relevant data.

  • Related