我知道如何使用以下形式解析XML文档:
<tagname> valueIWant </tagname>
但是,我现在试图获取的元素是
形式<photo farm="9" id="8147664661" isfamily="0" isfriend="0" ispublic="1"
owner="8437609@N04" secret="4902a217af" server="8192" title="Rainbow"/>
我通常使用cel.getTextContent()
来返回值,但在这种情况下这不起作用。 cel.getAttributes()
也没有,我认为它会起作用......
理想情况下,我需要获取id和所有者数值。但是,如果有人可以帮助解决所有这些问题,那么我可以处理删除以后我不想要的部分。
答案 0 :(得分:1)
您要检索的内容是使用Element附加的不同属性的值。看看使用getAttribute(String name)
方法来实现这个
如果要检索所有属性,可以使用getAttributes()
完成所有操作并迭代完成。这两种方法的一个例子可能是这样的:
private void getData(Document document){
if(document == null)
return;
NodeList list = document.getElementsByTagName("photo");
Element photoElement = null;
if(list.getLength() > 0){
photoElement = (Element) list.item(0);
}
if(photoElement != null){
System.out.println("ID: "+photoElement.getAttribute("id"));
System.out.println("Owner: "+photoElement.getAttribute("owner"));
NamedNodeMap childList = photoElement.getAttributes();
Attr attribute;
for(int index = 0; index < childList.getLength(); index++){
if(childList.item(index).getNodeType() == Node.ATTRIBUTE_NODE){
attribute = ((Attr)childList.item(index));
System.out.println(attribute.getNodeName()+" : "+attribute.getNodeValue());
}else{
System.out.println(childList.item(index).getNodeType());
}
}
}
}
答案 1 :(得分:0)
类似的东西:
Element photo = (Element)yournode;
photo.getAttribute("farm");
将获取farm属性的值。您需要将节点视为元素才能访问这些属性(doc)。