开发者

Get the name of all attributes in a XML-File

Hey I have an XML file and I would like to navigate to a given node and grab the name of all Attributes to that node.

For example: (XML File)

<RootName>
    <SubNode>
    <Attribute1>Value 1</Attribute1>
    <Attribute2>Value 2</Attribute2>  
</SubNode> 
</RootName>

Here is my code so far: (Java Code)

File file = new File("data.xml");
try
    {    
        /* Parse File */
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document doc = builder.parse(file);

        /* Find Starting Tag */
        NodeList nodes = doc.getElementsByTagName(StartTag);
        for (int i = 0; i < nodes.getLength(); i++)
        {
            Element element = (Element) nodes.item(i);
            System.out.println(element);

        }

Now I know you can find a specific attribute given the name

String name = element.getAttribute("Attribute1");    

But I would开发者_JAVA技巧 like to find all these names dynamically.

Thanks in advance

-Scott


What you are looking for are the Elements. Here is a sample on how to get the Elements in an XML:

import java.io.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.*;

public class DOMElements{
   static public void main(String[] arg){
     try {
       BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
       System.out.print("Enter XML File name: ");
       String xmlFile = bf.readLine();
       File file = new File(xmlFile);
       if(file.exists()){
         // Create a factory
         DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
         // Use the factory to create a builder
         DocumentBuilder builder = factory.newDocumentBuilder();
         Document doc = builder.parse(xmlFile);
         // Get a list of all elements in the document
         NodeList list = doc.getElementsByTagName("*");
         System.out.println("XML Elements: ");
         for (int i=0; i<list.getLength(); i++) {
           // Get element
           Element element = (Element)list.item(i);
           System.out.println(element.getNodeName());
         }
       }
       else{
         System.out.print("File not found!");
       }
     }
     catch (Exception e) {
       System.exit(1);
     }
   }
}

Also see my comment below your question on how to properly design XML and when to use elements, and when to use attributes.


element.getAttributes(); gets you a org.w3c.dom.NamedNodeMap. You can loop through this using the item(int index) method to get org.w3c.dom.Attr nodes, and get the names of those from the getName() method.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜