简体   繁体   中英

Reading multi-node and attribute XML in Java

My XML is as follows:-

<myxml>
    <resource name='book'>
        <acl>
            <ace person='bob' rights='rw' />
            <ace person='john' rights='w' />
        </acl>
    </resource>

    <resource name='dvd'>
        <acl>
            <ace person='bob' rights='w' />
        </acl>
    </resource>
</myxml>

I am having trouble reading this XML document.

Here is the code I tried.

    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
                .newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory
                .newDocumentBuilder();
        Document document = documentBuilder.parse(new File(fileName));

    Element rootElement = xmlDocument.getDocumentElement();

    NodeList resourceList= rootElement.getElementsByTagName("resource");
    for (int i = 0; i < resourceList.getLength(); i++) {
        Node node = resourceList.item(i);
        Element element = (Element) node;
        String resourceName= element.getAttribute("name");
    }

Basically I want to print like "this book can be used by this person with xyz permission".

I can get the name of the book by String objectName= element.getAttribute("name") . After this I can't go.

I tried by getting child nodes but keep on getting nulls.

Any suggestions?

One option is use element.getElementsByTagName("ace") to retrieve the ace elements you're looking for:

    NodeList aceList = element.getElementsByTagName("ace");
    for(int j= 0; j < aceList.getLength(); j++){
        Element ace = (Element) aceList.item(j);
        String person = ace.getAttribute("person");
    }

You just need another for loop nested inside to process <ace> elements.

NodeList resourceList = rootElement.getElementsByTagName("resource");
for (int i = 0; i < resourceList.getLength(); i++) {
    Element resource = (Element) resourceList.item(i);
    String book = resource.getAttribute("name");
    NodeList aceList = resource.getElementsByTagName("ace");
    for (int j = 0; j < aceList.getLength(); j++) {
        Element ace = (Element) aceList.item(j);
        System.out.println("'" + book + "' can be used by '"
                + ace.getAttribute("person") + "' with '"
                + ace.getAttribute("rights") + "' permission.");
    }
}

Output :

'book' can be used by 'bob' with 'rw' permission.
'book' can be used by 'john' with 'w' permission.
'dvd' can be used by 'bob' with 'w' permission.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM