我的XML如下: -
<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>
我无法阅读此XML文档。
这是我试过的代码。
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");
}
基本上我想打印像“这本书可以被xyz许可的人使用”。
我可以通过String objectName= element.getAttribute("name")
获取该书的名称。在此之后我不能去。
我尝试通过获取子节点但继续获取空值。
有什么建议吗?
答案 0 :(得分:0)
一个选项是使用element.getElementsByTagName(“ace”)来检索您正在寻找的ace元素:
NodeList aceList = element.getElementsByTagName("ace");
for(int j= 0; j < aceList.getLength(); j++){
Element ace = (Element) aceList.item(j);
String person = ace.getAttribute("person");
}
答案 1 :(得分:0)
您只需要嵌套在其中的另一个for
循环来处理<ace>
元素。
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.");
}
}
输出:
'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.