Search code examples
javajdom-2

Java:How to get Attribute name from xml in Java?(JDOM)


Java: How to get Attribute Name of the node Using JAVA-JDOM? For Example,

<xml>
    <Test id="001"></Test>
</xml>

The Output Should be:

id

My Java Program: In ______ Needs to get Attribute Name of node which as it is in Source file. This Program Just adds "_Test" to all nodes in the xml File and replace the same file.

try
    {
    XMLOutputter  xmlOut = new XMLOutputter();
    SAXBuilder builder = new SAXBuilder();
    File xmlFile = new File("D://Test//sample.xml");
    Document document = (Document) builder.build(xmlFile);
    Element rootNode = document.getRootElement();
    String Original_data=xmlOut.outputElementContentString(rootNode);
    String Test_Data="",Output_Data;
    List<?> list = rootNode.getChildren();
    PrintStream out = new PrintStream(new FileOutputStream("D://Test/sample.xml"));
    Element node=null;
    for(int i=0;i<list.size();i++)
      {
        node=(Element) list.get(i);
        Test_Data+="<"+node.getName()+"_Test "+__________+"="+node.getAttributeValue(________)+">"; //In ______ Needs to get Only Name of Attribute.

        List<?> n_list=node.getChildren();
        Element node2=null;
        for(int j=0;j<n_list.size();j++)
        {
            node2=(Element) n_list.get(j);

              String Str = new String(xmlOut.outputString(node2));
              Test_Data+=Str.replace(node2.getName(),node2.getName()+"_Test");
        }
        Test_Data+="</"+node.getName()+"_Test>";
      }
    out.println("<"+rootNode.getName()+">"+Original_data+Test_Data+"</"+rootNode.getName()+">");
    }

Sample.xml

 <?xml version="1.0" encoding="UTF-8" standalone="no"?>
<catalog>
 <book id="bk101_Test">
  <author>_Worked</author>
  <title>XML Developer's Guide</title>
  <genre>Computer</genre>
  <price>44.95</price>
  <publish_date>2000-10-01</publish_date>
  <description>An in-depth look at creating applications 
  with XML.</description>    
</book>
  <book id="bk112_Test">
  <author>Galos, Mike</author>
  <title>Visual Studio 7: A Comprehensive Guide</title>
  <genre>Computer</genre>
  <price>49.95</price>
  <publish_date>2001-04-16</publish_date>
  <description>Microsoft Visual Studio 7 is explored in depth,
  looking at how Visual Basic, Visual C++, C#, and ASP+ are 
  integrated into a comprehensive development 
  environment.</description>    
</book>
</catalog>

Solution

  • This Solves My Problem

    node.getAttributes().get(0).getName()