4

我知道如何在表单中使用 DOM 解析 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 和 owner 数值。但是,如果有人可以帮助如何获得所有这些,那么我可以处理删除我以后不想要的部分。

4

2 回答 2

1

您要检索的是元素附加的不同属性的值。看看使用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());
            }
        }
    }
}
于 2012-11-02T15:22:20.273 回答
0

就像是:

Element photo = (Element)yournode;
photo.getAttribute("farm");

将为您提供农场属性的值。您需要将节点视为元素才能访问这些属性 ( doc )。

于 2012-11-02T15:25:11.307 回答