Search code examples
recursiondom4j

print all attributes in a xml by recursive method


The problem is why I can't find any attributes from the rootElement?

my xml is

<?xml version="1.0" encoding="GBK"?>

<AccountInfos>
  <!--this is a test for dom4j-->
  <AccountInfo1 WebsiteName="ÐÂÀË" Account="123">Account1</AccountInfo1>
  <AccountInfo2 WebsiteName="ÍøÒ×" Account="123">Account2</AccountInfo2>
</AccountInfos>

and my code is like this

    private void treeWalker(Element element)
{
    int size = element.nodeCount();
    for (int i = 0; i < size; i++)
    {
        Node node = element.node(i);
        if (node instanceof Element)
        {
            treeWalker((Element) node);
        }
        else if(node instanceof Attribute)
        {
            Attribute attribute=(Attribute)node;
            System.out.println(attribute.getName()+":"+attribute.getValue());
        }
        else 
        {
            continue;
        }
    }
}

when I debug in this method I can‘t go into the second if block


Solution

  • Attributes are not considered part of the Element (or Branch, actually) content (such as Elements, Comments or Text nodes). You must retrieve then specially, e.g. with an attributeIterator().