简体   繁体   中英

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 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM