获取XML节点的值

4

当XML文档以以下形式出现时,我知道如何使用DOM解析:

<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的数值。不过,如果有人能帮忙获取全部内容,那么我之后可以删除不需要的部分。


这并不是任何特定语言中必须有效的格式,但它反映了XML通常的结构方式。 string nine = doc.attributes ["farm"] - Sam I am says Reinstate Monica
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());
            }
        }
    }
}

@user1766153:很高兴能帮忙。我更新了我的答案,为你提供了一个检索特定属性或同时检索所有属性的示例。希望这也能有所帮助 :) - Sujay

0

类似这样的:

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

将会获取到农场属性的值。您需要将节点视为元素,才能访问这些属性(doc)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接